如何使用ComboBox SelectionChanged事件更改StackPanel颜色?

时间:2018-06-15 04:40:21

标签: c# wpf vb.net

以下xaml代码是okey。

<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;
}

提前致谢

2 个答案:

答案 0 :(得分:0)

你可以这样使用。

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);
    }

答案 1 :(得分:0)

您可以在不更改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对象,然后使用名称Brush创建BrushConverter属性(&#34;红色,&#34;蓝色&#34;等)和 - pkg - runs - __init__.py - script.py - data - subdata - __init__.py - datascript.py 类。