<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
來定義屬性