2016-11-25 94 views
2
<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"; 
     } 
    } 

和转换器类有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; 
    } 

当我做bi nding在XAML代码工作:

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

但是当我尝试其绑定到ViewModelProperty的“RequiredUnit”对象始终是零。

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

回答

0

其原因是因为您试图从资源绑定到视图模型属性,但datacontext对资源不可用。在您的输出日志中,您必须获得绑定表达式错误。看看输出窗口。

有多种方式可以使这项工作。 一种方法是给你的窗前,仿佛X名称:NAME =“主窗口”,然后在你的绑定也一样:

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

另一种方法是使用相对源绑定它做的事。

+1

你的绑定是的,你是对我有datacontext的问题。我做了两种方法,但我仍然没有解决问题。 – leapold

0

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

,并与x:reference

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