【问题标题】:How to bind ViewModel Property to the dependency property in the convertor如何将 ViewModel 属性绑定到转换器中的依赖属性
【发布时间】:2016-11-25 21:11:06
【问题描述】:
<Window.Resources>
    <local:WeightConverter x:Key="weightConverter" RequiredUnit="{Binding VmProp}" /> 

 <TextBlock Text="{Binding Weight, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource weightConverter}}" />



public MainWindow()
    {
        InitializeComponent();
        DataContext = new MyViewModel();

在 MyViewModel 我有常规属性

    private string vmProp;

    public string VmProp
    {
        get
        {
            return "kg";
        }
    }

Convertor 类有 DependencyProperty 是:

 public class WeightConverter : DependencyObject, IValueConverter
{
    public static readonly DependencyProperty RequiredUnitProperty = DependencyProperty.Register("RequiredUnit", typeof(string), typeof(WeightConverter), null);
    public string RequiredUnit
    {
        get
        {
            return (string)this.GetValue(RequiredUnitProperty);
        }

        set
        {
            this.SetValue(RequiredUnitProperty, value);
        }
    }


    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
                   double dblValue;

        if (double.TryParse(value.ToString(), out dblValue))
        {
            if (this.RequiredUnit == "kg")
            {
                return dblValue;
            }

            else
            {
                return dblValue * 10;
            }

            return dblValue;
        }

        return 0;
    }

当我在 XAML 中进行绑定时,代码可以工作:

    <Window.Resources>
    <local:WeightConverter x:Key="weightConverter" RequiredUnit="kg"/>  

但是当我尝试将它绑定到 ViewModelProperty 时,'RequiredUnit' 对象始终为空。

如何将依赖属性绑定到 ViewModel 属性?

【问题讨论】:

    标签: c# wpf xaml mvvm


    【解决方案1】:

    其 null 的原因是因为您试图从资源绑定到视图模型属性,但数据上下文对资源不可用。在您的输出日志中,您一定会遇到绑定表达式错误。看看输出窗口。

    有多种方法可以让这个工作。 一种方法是给你的窗口一个名字,比如 x:Name="MainWindow" 然后在你的绑定中做这样的事情:

    <local:WeightConverter x:Key="weightConverter" RequiredUnit="{Binding DataContext.VmProp, ElementName=MainWindow}" />
    

    另一种方法是使用相对源绑定。

    【讨论】:

    • 是的,你是对的,我遇到了数据上下文的问题。两种方法我都做了,但还是没有解决问题。
    【解决方案2】:

    x:Name="leapold" 放入您的窗口/用户控件

    并使用x:reference进行绑定

    <local:WeightConverter x:Key="weightConverter" RequiredUnit="{Binding DataContext.VmProp, Source={x:Reference leapold}}"/>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-14
      • 1970-01-01
      • 2013-10-09
      • 2017-07-25
      • 2020-12-22
      • 2013-03-30
      • 1970-01-01
      • 2016-01-22
      相关资源
      最近更新 更多