绑定转换器,带有单行语法的paramater。

问题描述 投票:0回答:1

我基本上是想在一个linetag中制定以下的Binding条件。

<Rectangle.Fill>
     <Binding Path="Contents.Value">
          <Binding.Converter>
               <localVM:SquareConverter Empty="White" Filled="Black" Unknown="Gray"/>
           </Binding.Converter>
      </Binding>
</Rectangle.Fill>

我不知道如何指定上面的参数。Empty="white" Filled="Black" Unkown="gray"

我目前的情况是这样的。

 <Button Background="{Binding Path=Contents.Value, Converter={StaticResource localVM:SquareConverter}, ConverterParameter={ }}">

我给它的资源很好,我想,现在我找不到如何在语法上正确地指定参数?

P.S.不用担心上下文的问题,按钮背景是通过控件模板等映射成矩形填充的。

wpf converters ivalueconverter
1个回答
0
投票

你可能已经注意到了,你可以传递给Converter的参数数量只有1个,你可以传递一个字符串数组或者其他什么,但是我相信把所有的参数都放在一个字符串中会更容易写和处理。例如 "Empty=White|Filled=Black|Unknown=Gray"

你的转换器应该是这样的:

public class SquareConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is string arg && parameter is string str)
        {
            string[] splits = str.Split("|"); // split by the delimiter
            var colorConverter = new ColorConverter(); // required to convert invariant string to color
            foreach (var kv in splits)
            {
                if(kv.StartsWith(arg, StringComparison.OrdinalIgnoreCase))
                {
                    var v = kv.Split("=")[1]; // get the value from key-value
                    var color = (Color)colorConverter.ConvertFromInvariantString(v); // convert string to color
                    var brush = new SolidColorBrush(color); // convert color to solid color brush
                    return brush;
                }
            }
        }

        return default;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

在你的xaml中

xmlns:c="clr-namespace:WpfApp.Converters"

<Window.Resources>
    <c:SquareConverter x:Key="SquareConverter"/>
</Window.Resources>

<Rectangle Fill="{Binding Path=Contents.Value,
                          Converter={StaticResource SquareConverter},
                          ConverterParameter='Empty=White|Filled=Black|Unknown=Gray'}"/>
© www.soinside.com 2019 - 2024. All rights reserved.