我對WPF比較陌生,一直在嘗試一些小測試來提高我的知識。我目前正在嘗試使用組合框選擇一個項目,并根據選擇,使用IValueConverter更改主窗體背景的顏色,如下所示:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if(value != null)
{
if (value.ToString() == "Male")
{
return new SolidColorBrush(Color.FromArgb(255, 27, 161, 226));
}
else
{
return new SolidColorBrush(Color.FromArgb(255, 216, 0, 115));
}
}
return null;
}
我的問題是該值返回“System.Windows.Controls.ComboBoxItem:Female“或System.Windows.Controls.ComboBoxItem:Male。實施這種比較的正確方法是什么?
我的完整主窗口Xaml是:
<Window x:Class="MVVM.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MVVM"
xmlns:m="clr-namespace:MVVM.Models"
xmlns:vm="clr-namespace:MVVM.ViewModels"
xmlns:converters="clr-namespace:MVVM.ViewModels.Converters"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<m:Person x:Key="person"/>
<converters:BackgroundConverter x:Key="converter"/>
<vm:ViewModelBase x:Key="viewModel"/>
</Window.Resources>
<Grid DataContext="{Binding Source={StaticResource person}}"
Background="{Binding Gender, Converter={StaticResource converter}}">
<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
<TextBox Text="{Binding Name, Mode=TwoWay}"/>
<TextBox Text="{Binding LastName, Mode=TwoWay}"/>
<TextBlock Text="{Binding FullName}" FontSize="20"/>
<ComboBox SelectedValue="{Binding Gender, Mode=TwoWay}">
<ComboBoxItem>Male</ComboBoxItem>
<ComboBoxItem>Female</ComboBoxItem>
</ComboBox>
<Button Content="Simple Command" Command="{Binding SimpleCommand, Source={StaticResource viewModel}}"/>
</StackPanel>
</Grid>
謝謝你的幫助。
您可以將字符串添加到組合框中。ComboBoxItems將在后臺創建:
其中
sys
在命名空間聲明中: