注意:如果您正在开发 WPF 应用程序,mm8 使用 DataTrigger 的答案非常棒。
在 WPF 和 UWP 中,您可以创建 IValueConverter 接口的自定义实现,以使用几乎相同的代码实现此目的。基本上,它会根据您定义的规则将您的字符串输入转换为布尔值。
WPF:
public class StringToBooleanConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value.ToString().Equals("y");
}
// This is not really needed because you're using one way binding but it's here for completion
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if(value is bool)
{
return value ? "y" : "n";
}
}
}
UWP:
上面的代码除了Convert和ConvertBack方法中的最后一个参数外完全一样:
public object Convert(object value, Type targetType, object parameter, string language) { }
public object ConvertBack(object value, Type targetType, object parameter, string language) { }
以下内容对于 WPF 和 UWP 大致相同。您可以使用 XAML 中的转换器将字符串转换为布尔值:
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="IsSelected" Value="{Binding f_selected, Mode=OneWay, Converter={StaticResource StringToBooleanConverter}}" />
</Style>
</ListBox.ItemContainerStyle>
另外,记得在开头介绍转换器:
<Window.Resources>
<local:YesNoToBooleanConverter x:Key="StringToBooleanConverter" />
</Window.Resources>