【问题标题】:Convert y / n to true / false in XAML在 XAML 中将 y / n 转换为 true / false
【发布时间】:2019-08-27 10:56:18
【问题描述】:

我使用以下代码预选了列表框中的一些行:

<ListBox.ItemContainerStyle>
    <Style TargetType="{x:Type ListBoxItem}">
       <Setter Property="IsSelected" Value="{Binding f_selected, Mode=OneWay}" />
    </Style>
</ListBox.ItemContainerStyle>

代码中 f_selected 的值只能是真或假,但在 DB 上的值是 y/n。 我使用了一个技巧,通过使用对象将 y/n 转换为 true/false,但高层要求我只在对象中使用 y/n。 有没有办法使用字符串而不是布尔值或在 XAML 或视图模型中进行转换?

感谢您的帮助,一如既往地为糟糕的英语感到抱歉。

【问题讨论】:

  • 你知道为什么要求只使用字符串吗?这可能会泄露应该如何实施。

标签: c# xaml


【解决方案1】:

在 WPF 中,您可以使用 DataTrigger:

<ListBox.ItemContainerStyle>
    <Style TargetType="{x:Type ListBoxItem}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding f_selected}" Value="y">
                <Setter Property="IsSelected" Value="True" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</ListBox.ItemContainerStyle>

在 UWP 中,您可以使用 DataTriggerBehavior 完成相同的操作。

【讨论】:

    【解决方案2】:

    注意:如果您正在开发 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>
    

    【讨论】:

      猜你喜欢
      • 2016-12-01
      • 2020-07-06
      • 2014-01-17
      • 1970-01-01
      • 1970-01-01
      • 2011-12-16
      • 2021-06-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多