首页 > 解决方案 > 如何使用 ComboBox SelectionChanged 事件更改 StackPanel 颜色?

问题描述

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

提前致谢

标签: c#wpfvb.net

解决方案


你可以这样使用。

更改ColorsBrushes

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

推荐阅读