我對 WPF 比較陌生,并不斷嘗試一些小測驗來提高我的知識。我目前正在嘗試使用組合框來選擇一個專案,并根據選擇,使用 IValueConverter 更改 MainForm 背景的顏色,如下所示:
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。實作這種比較的正確方法是什么?
我的完整 MainWindow 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>
謝謝您的幫助。
uj5u.com熱心網友回復:
您可以將字串添加到 ComboBox 中。ComboBoxItems 將在幕后創建:
<ComboBox SelectedValue="{Binding Gender, Mode=TwoWay}">
<sys:String>Male</sys:String>
<sys:String>Female</sys:String>
</ComboBox>
其中sys一個命名空間宣告:
xmlns:sys="clr-namespace:System;assembly=mscorlib"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/360481.html
