首页 / C# / c# – 在WPF中创建自定义UI元素
c# – 在WPF中创建自定义UI元素
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 在WPF中创建自定义UI元素,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2051字,纯文字阅读大概需要3分钟。
内容图文
![c# – 在WPF中创建自定义UI元素](/upload/InfoBanner/zyjiaocheng/795/dfc600a94fd541909fec9068a03f2eed.jpg)
我的代码中有几个带有标签的TextBox,它们使用以下XAML实现:
<DockPanel HorizontalAlignment="Right">
<TextBlock Foreground="Black" Padding="0,0,10,0">Serial Number:</TextBlock>
<TextBox Width="150" IsReadOnly="True" BorderBrush="Gainsboro" Height="20"></TextBox>
</DockPanel>
我可以通过以下方式减少一些复制的代码:
<DockPanel HorizontalAlignment="Right">
<TextBlock Style="{StaticResource CstmTextBoxLbl}">Serial Number:</TextBlock>
<TextBox Style="{StaticResource CstmTextBox}"></TextBox>
</DockPanel>
但它仍然有点冗长.有可能做这样的事情:
<controls:CstmTextBox Style="{StaticResource CstmTextBox}" LabelText="Serial Number:" Text=""/>
CstmTextBox将实现一次获得相同视觉效果所需的任何XAML,并且我可以访问代码中的TextBlock文本和TextBox文本.如
CstmTextBox textbox;
textbox.LabelText = "Serial Number:";
String some_text = textbox.Text;
textbox.Text = "....";
解决方法:
UserControl或CustomControl满足您的需求.这是CustomControl的代码.
C#:
public class CstmTextBox : Control
{
public string LabelText
{
get
{
return (string)GetValue (LabelTextProperty);
}
set
{
SetValue (LabelTextProperty, value);
}
}
public static readonly DependencyProperty LabelTextProperty =
DependencyProperty.Register ("LabelText", typeof (string), typeof (CstmTextBox), new PropertyMetadata (string.Empty));
public string Text
{
get
{
return (string)GetValue (TextProperty);
}
set
{
SetValue (TextProperty, value);
}
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register ("Text", typeof (string), typeof (CstmTextBox), new PropertyMetadata (string.Empty));
}
XAML:
<Style TargetType="{x:Type controls:CstmTextBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type controls:CstmTextBox}">
<DockPanel HorizontalAlignment="Right">
<TextBlock Foreground="Black" Padding="0,0,10,0" Text="{TemplateBinding LabelText}"/>
<TextBox Width="150" IsReadOnly="True" BorderBrush="Gainsboro" Height="20" Text="{TemplateBinding Text}"/>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
将样式添加到资源并使用新控件:
<controls:CstmTextBox LabelText="abcde" Text="1234"/>
内容总结
以上是互联网集市为您收集整理的c# – 在WPF中创建自定义UI元素全部内容,希望文章能够帮你解决c# – 在WPF中创建自定义UI元素所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。