自定义WPF UI控件,并实现binding属性
<UserControl x:Class="CostWPF.UserControls.LabelComboBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="31.05" d:DesignWidth="360" x:Name="labelComboBox">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="30*"></ColumnDefinition>
<ColumnDefinition Width="70*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock TextWrapping="Wrap" Text="{Binding Label, ElementName=labelComboBox}" VerticalAlignment="Center" TextAlignment="Right"></TextBlock>
<ComboBox Grid.Column="1" Name="CBB_Content" ItemsSource="{Binding Items, ElementName=labelComboBox}" VerticalAlignment="Center" SelectedItem="{Binding Value, ElementName=labelComboBox}" Margin="10,0,0,0">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Text, ElementName=labelComboBox}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
</UserControl>
public static readonly DependencyProperty TextTProperty = DependencyProperty.Register("Label", typeof(string), typeof(LabelComboBox));
public string Label
{
get { return (string)GetValue(TextTProperty); }
set
{
SetValue(TextTProperty, value);
}
}
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register(
"Value", typeof(KeyText), typeof(LabelComboBox), new FrameworkPropertyMetadata(null) { BindsTwoWayByDefault = true });
public KeyText Value
{
get { return GetValue(ValueProperty) as KeyText; }
set
{
SetValue(ValueProperty, value);
}
}
public static readonly DependencyProperty ItemsProperty =
DependencyProperty.Register(
"Items", typeof(List<KeyText>), typeof(LabelComboBox), new FrameworkPropertyMetadata(new List<KeyText>()) { BindsTwoWayByDefault = true });
public List<KeyText> Items
{
get { return GetValue(ItemsProperty) as List<KeyText>; }
set
{
SetValue(ItemsProperty, value);
}
}
重点:
1、在UserControl
上,加一个x:Name
, 并在下边的所有绑定里,添加, ElementName=x:Name
2、在后台代码里,需要使用DependencyProperty
来定义属性
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南