我有以下xaml代码:
<Window x:Class="WPF_les_3.Oefening_4"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Oefening_4" Height="300" Width="300">
<StackPanel Width="auto" Margin="20px">
<ComboBox Width="100" SelectionChanged="ComboBox_Selected" x:Name="comboBox">
<ComboBoxItem>
<StackPanel Orientation="Horizontal">
<Rectangle Fill="Red" Height="20" Width="20"/>
<TextBlock Text=" Red"/>
</StackPanel>
</ComboBoxItem>
<ComboBoxItem>
<StackPanel Orientation="Horizontal">
<Rectangle Fill="Yellow" Height="20" Width="20"/>
<TextBlock Text=" Yellow"/>
</StackPanel>
</ComboBoxItem>
<ComboBoxItem>
<StackPanel Orientation="Horizontal">
<Rectangle Fill="Green" Height="20" Width="20"/>
<TextBlock Text=" Green"/>
</StackPanel>
</ComboBoxItem>
</ComboBox>
</StackPanel>
如您所见,在我的ComboboxItems中,我有一个矩形和一个文本块。现在我想在处理我的selectionchanged事件时检索矩形的填充颜色(或文本块的文本,它是相同的),因此我可以根据所选颜色更改窗口的背景(是运动的目标。
答案 0 :(得分:2)
详细说明上面的评论,这是正确在WPF中实现所需内容的方式:
首先,创建一个包含可用颜色列表和SelectedColor属性的正确 ViewModel :
public class ColorsViewModel
{
public ObservableCollection<string> Colors { get; private set; }
private string _selectedColor;
public string SelectedColor
{
get { return _selectedColor; }
set
{
_selectedColor = value;
MessageBox.Show("Selected Color: " + value); //message box here to show the code is actually working.
}
}
//... More code here in a moment
}
然后,确保使用相关数据填充颜色集合。特别是在颜色的情况下,WPF内置的TypeConverters可以隐式地从(例如)string
转换为System.Windows.Media.Color
,因此我们可以利用它来简化代码并使用简单的字符串:
//Continuation of the above code
public ColorsViewModel()
{
Colors = new ObservableCollection<string>
{
"Red",
"Green",
"Blue",
"Yellow",
};
}
最后使用正确的DataBinding:
在XAML中创建UI<Window x:Class="WpfApplication3.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">
<ComboBox ItemsSource="{Binding Colors}"
SelectedItem="{Binding SelectedColor}"
VerticalAlignment="Center" HorizontalAlignment="Center">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Rectangle Fill="{Binding}" Height="20" Width="20"/>
<TextBlock Text="{Binding}"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Window>
结果:
答案 1 :(得分:1)
触发change事件,ComboBox.SelectedItem具有您需要的信息。 您必须像我的以下方法一样分析SelectedItem:
private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBoxItem comboBoxItem = this.comboBox.SelectedItem as ComboBoxItem;
if (comboBoxItem != null)
{
StackPanel stackPanel = comboBoxItem.Content as StackPanel;
if(stackPanel != null && stackPanel.Children[0] is Rectangle)
{
var fill = (stackPanel.Children[0] as Rectangle).Fill;
}
}
}
在这里你得到矩形的填充,可以处理这个或做你的东西。 但请耐心等待,此代码是为您准备的样本(ComboBoxItem,内容StackPanel,子项[0]为矩形)。改变将破坏过程;)