遵循xaml代码是可以的。
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ObjectDataProvider ObjectInstance="{x:Type Colors}" MethodName="GetProperties" x:Key="colorPropertiesOdp" />
</Window.Resources>
<Grid>
<StackPanel Name="StackPanel1" Width="200" Height="30" Background="Red" VerticalAlignment="Top"/>
<ComboBox Name="ComboBox1" Width="200" Height="30" ItemsSource="{Binding Source={StaticResource colorPropertiesOdp}}" SelectedValuePath="Name">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="18" Margin="0,0,0,2">
<Border x:Name="Border1" BorderThickness="1" CornerRadius="2" BorderBrush="Black" Width="50" VerticalAlignment="Stretch" Background="{Binding Name}"/>
<TextBlock Text="{Binding Name}" Margin="8,0,0,0"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
</Window>遵循vb.net代码是不安全的,需要修复。
Private Sub ComboBox1_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Handles ComboBox1.SelectionChanged
StackPanel1.Background = Border1.Background
End Sub遵循C#代码是不安全的,需要修复。
private void ComboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e) {
StackPanel1.Background = Border1.Background;
}提前感谢
发布于 2018-06-15 09:46:57
您可以像这样实现事件处理程序,而无需更改XAML:
private void ComboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBox cmb = sender as ComboBox;
PropertyInfo pi = cmb.SelectedItem as PropertyInfo;
if (pi != null)
{
Brush brush = (Brush)new BrushConverter().ConvertFromString(pi.Name);
brush.Freeze();
StackPanel1.Background = brush;
}
}ComboBox绑定到IEnumerable<PropertyInfo>,因此您将SelectedItem转换到当前选定的PropertyInfo对象,然后使用属性名称(“红色”、“蓝色”等)和BrushConverter类创建Brush。
发布于 2018-06-15 05:41:46
你可以这样用。
将Colors更改为Brushes。
<Window.Resources>
<ObjectDataProvider ObjectInstance="{x:Type Brushes}" MethodName="GetProperties" x:Key="colorPropertiesOdp" />
</Window.Resources>添加此事件处理程序:
<ComboBox Name="ComboBox1" Width="200" Height="30" SelectionChanged="ComboBox1_OnSelectionChanged" ItemsSource="{Binding Source={StaticResource colorPropertiesOdp}}" SelectedValuePath="Name">更改事件:
private readonly BrushConverter _converter = new BrushConverter();
private void ComboBox1_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var brush = ((PropertyInfo)this.ComboBox1.SelectedItem).Name;
this.StackPanel1.Background = (Brush)_converter.ConvertFromString(brush);
}https://stackoverflow.com/questions/50869209
复制相似问题