Search code examples
wpfmvvmbindingdependency-propertiescode-behind

Binding to a DependencyProperty via ViewModel has no effect


I've simplified my problem (it means that the principle is similar, but I don't want to cast a int to string ...):

MainWindow.xaml:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:WpfApplication1="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="500" Width="500">
    <Grid>

        <WpfApplication1:UserControl1 CurrentNumber="{Binding Path=TheSpecialNumber, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

    </Grid>
</Window>

In the Main Window is the UserControl1 appear. The usercontrol has a property Current Number. This I would like to bind the property TheSpecialNumber (the ViewModel).

MainWindow.xaml.cs:

namespace WpfApplication1
{
    public partial class MainWindow
    {
        private readonly ViewModel _viewModel;

        public MainWindow()
        {
            InitializeComponent();
            _viewModel = new ViewModel();
            DataContext = _viewModel;

            _viewModel.TheSpecialNumber = "8";
            _viewModel.UpdateTheSpecialNumberBinding();
        }
    }
}

ViewModel.cs:

namespace WpfApplication1
{
    class ViewModel : INotifyPropertyChanged
    {
        public string TheSpecialNumber { get; set; }

        public event PropertyChangedEventHandler PropertyChanged;

        public void UpdateTheSpecialNumberBinding()
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("TheSpecialNumber"));
            }
        }
    }
}

UserControl1.xaml:

<UserControl x:Class="WpfApplication1.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             Height="200" Width="300" Background="Aqua">
    <Grid Name="container">
        <ComboBox SelectedIndex="{Binding Path=CurrentNumberIndex, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
            <ComboBoxItem Height="20">0</ComboBoxItem>
            <ComboBoxItem Height="20">1</ComboBoxItem>
            <ComboBoxItem Height="20">2</ComboBoxItem>
            <ComboBoxItem Height="20">3</ComboBoxItem>
            <ComboBoxItem Height="20">4</ComboBoxItem>
            <ComboBoxItem Height="20">5</ComboBoxItem>
            <ComboBoxItem Height="20">6</ComboBoxItem>
            <ComboBoxItem Height="20">7</ComboBoxItem>
            <ComboBoxItem Height="20">8</ComboBoxItem>
            <ComboBoxItem Height="20">9</ComboBoxItem>
        </ComboBox>
    </Grid>
</UserControl>

The UserControl is a ComboBox. This has 10 items. I want to always display the item that has the same number as the property Current Number. Therefore, the binding of Current Number Index.

UserControl1.xaml.cs:

using System;
using System.ComponentModel;
using System.Windows;

namespace WpfApplication1
{
    public partial class UserControl1 : INotifyPropertyChanged
    {
        public static readonly DependencyProperty CurrentNumberProperty = DependencyProperty.Register("CurrentNumber", typeof(string), typeof(UserControl1));

        public UserControl1()
        {
            InitializeComponent();
            container.DataContext = this;

            CurrentNumber = "5";
        }

        public string CurrentNumber
        {
            get { return (string)GetValue(CurrentNumberProperty); }
            set
            {
                SetValue(CurrentNumberProperty, value);
                OnPropertyChanged("CurrentNumberIndex");
            }
        }

        public int CurrentNumberIndex
        {
            get
            {
                return Convert.ToInt32(CurrentNumber);
            }
            set
            {
                CurrentNumber = Convert.ToString(value);
            }
        }

        #region Implementation of INotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion Implementation of INotifyPropertyChanged
    }
}

Now my question. Why only the ComboBox items is displayed with the content of 0, if I do in the MainWindow (via ViewModel) the set 8? Even if I make a breakpoint in the setter of Current Number, I stop only once, namely at the 5, but not at the 8.


Solution

  • You might "destroy" the binding between TheSpecialNumber and CurrentNumber by setting CurrentNumber=5 manuelly. Remove this part and try again.

    EDIT: Ok, if this doesnt work, try the following:

    1. Add a new PropertyChangedCallback to your PropertyMetaData:

      public static readonly DependencyProperty CurrentNumberProperty = DependencyProperty.Register("CurrentNumber", typeof(string), typeof(UserControl1), new PropertyMetadata( new PropertyChangedCallback(CurrentNumberPropertyChanged))); 
      
    2. Set CurrentNumber in this Method like:

      private static void CurrentNumberPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
      {
          UserControl1 uc1 = (UserControl1)dependencyObject;
          uc1.CurrentNumber = (string)dependencyPropertyChangedEventArgs.NewValue;
      }