c# - 如何将 ViewModel 属性绑定(bind)到转换器中的依赖属性

标签 c# wpf xaml mvvm

<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/

相关文章:

c# - 绑定(bind)手势识别器

c# - 处理返回 HttpWebResponse 的方法中的错误

c# - 使用交互触发器调用可见性更改方法 WPF

c# - 对其他应用程序进行同步调用

c# - Caliburn Micro是否从版本1.1更改为1.5.1?

WPF 以编程方式实例化用户控件以将其呈现为 PNG

c# - 如何以增量方式调整 WPF 窗口的大小?

c# - 如何检查 Google AdSense 在我的 ASP.NET 网站中是否正常工作?

c# - WPF DVC :Lineseries Style and axes settings using c#

wpf - 在 XAML 中包装另一个控件的控件模板