具有绑定依赖属性的 IValueConverter [英] IValueConverter with Bound Dependency Properties

查看:16
本文介绍了具有绑定依赖属性的 IValueConverter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据要绑定的对象中标识的单位系统在运行时确定某些绑定的 TextBlocksStringFormat.

I need to determine the StringFormat of some bound TextBlocks at runtime based on the unit system identified in the object to be bound.

我有一个转换器,我想绑定到它的依赖属性.Bound 值用于确定转换过程.

I Have a converter with a Dependency Property that I would like to Bind to. The Bound value is used in determining the conversion process.

public class UnitConverter : DependencyObject, IValueConverter
{
    public static readonly DependencyProperty IsMetricProperty =
        DependencyProperty.Register("IsMetric", typeof(bool), typeof(UnitConverter), new PropertyMetadata(true, ValueChanged));

    private static void ValueChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
    {
        ((UnitConverter)source).IsMetric = (bool)e.NewValue;
    }

    public bool IsMetric
    {
        get { return (bool)this.GetValue(IsMetricProperty); }
        set { this.SetValue(IsMetricProperty, value); }
    }

    object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (IsMetric)
            return string.Format("{0:0.0}", value);
        else
            return string.Format("{0:0.000}", value);
    }

    object IValueConverter.ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

我声明转换器

<my:UnitConverter x:Key="Units" IsMetric="{Binding Path=IsMetric}"/>

并绑定TextBlock

and bind the TextBlock

<TextBlock Text="{Binding Path=Breadth, Converter={StaticResource Units}}" Style="{StaticResource Values}"/>

无论如何,我收到以下错误:

Never the less, I get the following error:

System.Windows.Data 错误:2:找不到目标元素的管理 FrameworkElement 或 FrameworkContentElement.BindingExpression:Path=IsMetric;数据项=空;目标元素是UnitConverter"(HashCode=62641008);目标属性是'IsMetric'(类型'Boolean')

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=IsMetric; DataItem=null; target element is 'UnitConverter' (HashCode=62641008); target property is 'IsMetric' (type 'Boolean')

我猜这是在我设置数据上下文之前初始化的,因此没有什么可以绑定 IsMetric 属性.我怎样才能达到预期的结果?

I guess this is initialising before I set the datacontext and therefore there is nothing to bind the IsMetric property to. How can I achieve the desired result?

推荐答案

假设 BreadthIsMetric 是同一个数据对象的属性,你可以使用 MultiBinding 与 多值转换器:

Provided that Breadthand IsMetric are properties of the same data object, you might use a MultiBinding in conjunction with a multi value converter:

<TextBlock>
    <TextBlock.Text>
        <MultiBinding Converter="{StaticResource UnitMultiValueConverter}">
            <Binding Path="Breadth" />
            <Binding Path="IsMetric" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

使用这样的转换器:

public class UnitMultiValueConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        double value = (double)values[0];
        bool isMetric = (bool)values[1];
        string format = isMetric ? "{0:0.0}" : "{0:0.000}";
        return string.Format(format, value);
    }

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

您的方法的问题在于,当 UnitConverter 被声明为资源时,它没有 DataContext,以后将永远不会获得.

The problem with your approach is that when the UnitConverter is declared as resource it does not have a DataContext, and it will never get one later on.

还有一件更重要的事情:UnitConverter.IsMetricValueChanged 回调是无稽之谈.它再次设置了刚刚更改的相同属性.

And one more important thing: the ValueChanged callback for UnitConverter.IsMetric is nonsense. It sets the same property again which was just changed.

这篇关于具有绑定依赖属性的 IValueConverter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆