c# - 如何使用 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;
}
提前致谢
解决方案
你可以这样使用。
更改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);
}
推荐阅读
- amazon-web-services - 访问 AWS 为已部署资源自动生成的 URL
- spss - 向 SPSS 数据集中的所有变量添加值 + 值标签
- r - 需要 R 函数来比较一个文件中的缺失值并在另一个文件中更新
- python - 使用 psycopg2 的“ELF 文件操作系统 ABI 无效”
- ffi - 如何将函数分配给 Rebol 结构成员
- javascript - js切换多个div
- android-tv - 将 android TV 应用程序部署到 beta 测试人员的好方法是什么
- css - 在角度模态动画中实现缩放效果
- oracle - PL/SQL 连接
- jquery - 如何从 CSV AJAX 请求修改 DataTables 列?