简体   繁体   English

使用Binding作为ConverterParameter

[英]Use Binding as ConverterParameter

I'm trying to use a value binding as converter parameter as shown in the code snippet below: 我正在尝试使用值绑定作为转换器参数,如下面的代码片段所示:

<Element
  Attribute="{Binding Value,
              Converter={StaticResource EqualityConverter},
              ConverterParameter={Binding CompareTo}}" />

The problem is, that the EqualityConverter::Convert() method is called with an instance of Binding as converter parameter ( CompareTo ) rather than the concrete value of the binding. 问题是,使用Binding实例作为转换器参数( CompareTo )调用EqualityConverter::Convert()方法,而不是绑定的具体值。

Is there a smarter way to solve it? 有更聪明的方法来解决它吗? I could obviously provide the converted property in my view model, but I would like to know if there is a similar working solution to the above one. 我显然可以在我的视图模型中提供转换后的属性,但我想知道是否有类似的工作解决方案。

Another, potentially simpler way to do this is to define a bindable property on the converter itself. 另一种可能更简单的方法是在转换器本身上定义一个可绑定属性。

public class CompareConverter: IValueConverter, INotifyPropertyChanged{
  private ComparisonType _comparison = ComparisonType.Equals;
  public ComparisonType Comparison {
    get {return _comparison; }
    set { _comparison = value; OnPropertyChanged(); }
  }

  private string _compareTo = null;
  public string CompareTo {
    get {return _compareTo; }
    set { _compareTo = value; OnPropertyChanged(); }
  }

  public event PropertyChangedEventHandler PropertyChanged;

  protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
  { 
    if (PropertyChanged != null) 
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
  } 

  public object Convert (object value, Type targetType, object parameter, 
     System.Globalization.CultureInfo culture)
  {
    bool result = false;
    switch (Comparison)...
    return result;
  } 
  ...
}

You can also do this by inheriting BindableObject and implementing bindable properties, you may need to do that if the binding context isn't carried into the resources. 您也可以通过继承BindableObject并实现可绑定属性来完成此操作,如果绑定上下文未被携带到资源中,您可能需要这样做。 If that's the case you can set it from code behind once in the constructor, after the Initialize method is called. 如果是这种情况,您可以在构造函数中从代码后面设置一次,在调用Initialize方法之后。

Your xaml would look like this: 你的xaml看起来像这样:

..
<ResourceDictionary>
  <myPrefix:CompareConverter x:Key="compareToY" Comparison="Equals" CompareTo="{Binding... }"/>
</ResourceDictionary>
...
<Control Value="{Binding X, Converter={StaticResource compareToY}}"/>

It may take a bit of tweaking by the result should be cleaner than multi-bindings 可能需要一些调整,结果应该比多绑定更干净

I was struggling with the same problem and not getting the data that i wanted. 我正在努力解决同样的问题而没有得到我想要的数据。 You can't bind to a "converterParameter", thats just how its made at the current date. 你不能绑定到“converterParameter”,这就是它在当前日期的制作方式。 But i really wanted to get some kind of data sent to the parameter. 但我真的想得到一些发送到参数的数据。 so i found a simple yet working solution and i hope it could work for you aswell. 所以我找到了一个简单但有效的解决方案,我希望它也适合你。 Start with giving CompareTo ax:Name="CompareTo" or whatever you want to call it. 首先给出CompareTo ax:Name =“CompareTo”或者你想要的任何东西。

         <Element
          Attribute="{Binding Value,
          Converter={StaticResource EqualityConverter},
          ConverterParameter={x:reference CompareTo}}" />

By doing x:reference its actually sending some data now, you just have to grab it. 通过x:引用它实际上现在发送一些数据,你只需抓住它。 For me the value i needed was the "string" value so that i could do certain "If" statements. 对我来说,我需要的值是“字符串”值,以便我可以做某些“如果”语句。 So you could do something similar to: 所以你可以做类似的事情:

    if(CompareTo == "myCoolString")
    {
      Value = "Well i guess i'm not so cool!"
    }

This is how i got my data from the parameter: 这是我从参数中获取数据的方式:

   public class MyConverter : IValueConverter
    {

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (parameter != null)
        {
            try
            {
                var image = parameter as Image;
                var src = image.Source as FileImageSource;

                if (src.File.ToString() == "coolimage.png")
                {
                    return "thumbsup.png";
                }
            }
            catch
            {
            }
        } 
    }

In my case i was working with and image and needed the to know if one image was "A" then "B" needed to change into image "C". 在我的情况下,我正在使用和图像,并需要知道一个图像是“A”,然后“B”需要转换为图像“C”。 This should work with other objects aswell. 这应该与其他对象一起使用。 With a little luck this will get you somewhat closer to a kind of simplistic "Multibinding" and answer. 运气不错,这会让你更接近一种简单的“多重绑定”和回答。

Hope this was helpful as its my first ever post on Stackoverflow! 希望这是我在Stackoverflow上的第一篇文章有​​用!

ConverterParameter is not a Dependency Property, hence you won't be able to bind any property. ConverterParameter不是依赖属性,因此您将无法绑定任何属性。 However, you can try using MultiBinding with MultiValueConverter. 但是,您可以尝试将MultiBinding与MultiValueConverter一起使用。

Code: 码:

<TextBox>
    <TextBox.Text>
        <MultiBinding Converter="{StaticResource MultiValueConverter}">
            <Binding Path="property1"/>
            <Binding Path="property2"/>
        </MultiBinding>
    </TextBox.Text>
</TextBox>
public class MultiValueConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, 
           object parameter, System.Globalization.CultureInfo culture)
    {
         property1 = values[0];
         property2 = values[1];
         // Do your logic with the properties here.
    }
    public object[] ConvertBack(object value, Type[] targetTypes, 
           object parameter, System.Globalization.CultureInfo culture)
    {

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM