简体   繁体   中英

How to bind ViewModel Property to the dependency property in the convertor

<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();

In the MyViewModel I have regular property

    private string vmProp;

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

And Convertor class has DependencyProperty is:

 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;
    }

When I do binding in XAML the code works:

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

But when I try to bind it to ViewModelProperty the 'RequiredUnit' object is always null.

How can I bind dependency property to ViewModel property?

The reason its null is because you are trying to bind to the view model property from the resources, but the datacontext is not available to the resource. In your output log, you must be getting a binding expression error. Have a look at the output window.

There are multiple ways to get this working. One way is to give your window a name like x:Name="MainWindow" and then in your binding do like:

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

Another way would be to do it using Relative Source binding.

Put x:Name="leapold" to your Window/Usercontrol

and make your binding with x:reference

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM