<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 中进行绑定(bind)时,代码有效:
<Window.Resources>
<local:WeightConverter x:Key="weightConverter" RequiredUnit="kg"/>
但是当我尝试将它绑定(bind)到 ViewModelProperty 时,“RequiredUnit”对象始终为 null。
如何将依赖属性绑定(bind)到 ViewModel 属性?
最佳答案
它为 null 的原因是因为您试图从资源绑定(bind)到 View 模型属性,但数据上下文对资源不可用。在您的输出日志中,您一定遇到了绑定(bind)表达式错误。查看输出窗口。
有多种方法可以让它发挥作用。 一种方法是给你的窗口起一个像 x:Name="MainWindow"这样的名字,然后在你的绑定(bind)中做这样的事情:
<local:WeightConverter x:Key="weightConverter" RequiredUnit="{Binding DataContext.VmProp, ElementName=MainWindow}" />
另一种方法是使用相对源绑定(bind)。
关于c# - 如何将 ViewModel 属性绑定(bind)到转换器中的依赖属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40812326/