0
我有自定義ComboBox
控件,它允許選擇顏色,如本文Color Picker using WPF Combobox中所述。更新自定義控件
我插入自定義ComboBox
在MainWindow
這樣:
<local:Colorpicker x:Name="brushesComboBox"></local:Colorpicker>
當我手動選擇的顏色,它工作正常,但如果我設置的顏色編程這樣的:
brushesComboBox.SelectedColor= new SolidColorBrush(Colors.Aquamarine);
組合框doesn`更新自己。
我知道我需要修改Colorpicker類的代碼,這樣當設置依賴屬性時,它將強制更新內部組合框中的選定索引。我怎麼做?
Colorpicker
類,XAML部分:
<UserControl x:Class="WpfParabola.Colorpicker"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfParabola"
xmlns:sys="clr-namespace:System;assembly=mscorlib" Name="uccolorpicker"
mc:Ignorable="d"
d:DesignHeight="20" d:DesignWidth="200">
<UserControl.Resources>
<ResourceDictionary>
<ObjectDataProvider MethodName="GetType"
ObjectType="{x:Type sys:Type}" x:Key="colorsTypeOdp">
<ObjectDataProvider.MethodParameters>
<sys:String>System.Windows.Media.Colors, PresentationCore,
Version=3.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35</sys:String>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
<ObjectDataProvider ObjectInstance="{StaticResource colorsTypeOdp}"
MethodName="GetProperties" x:Key="colorPropertiesOdp">
</ObjectDataProvider>
</ResourceDictionary>
</UserControl.Resources>
<Grid>
<ComboBox Name="superCombo"
ItemsSource="{Binding Source={StaticResource colorPropertiesOdp}}"
SelectedValuePath="Name"
SelectedValue="{Binding ElementName=uccolorpicker,
Path=SelectedColor}">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Width="50" Height="{Binding ElementName=FontSize+4}" Margin="2" Background="{Binding Name}"/>
<TextBlock TextAlignment="Left" VerticalAlignment="Center" Text="{Binding Name}"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
</UserControl>
Colorpicker
類,後面的代碼:
public partial class Colorpicker : UserControl
{
public Colorpicker()
{
InitializeComponent();
superCombo.SelectedIndex = 0;
}
public Brush SelectedColor
{
get { return (Brush)GetValue(SelectedColorProperty); }
set{SetValue(SelectedColorProperty, value);}
}
// Using a DependencyProperty as the backing store for SelectedColor. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SelectedColorProperty =
DependencyProperty.Register("SelectedColor", typeof(Brush), typeof(Colorpicker), new UIPropertyMetadata(null));
}