views:

35

answers:

2

I am working on WPF project. I create a usercontrol containing a combobox; which represent boolean value(True or false). And I register a DependencyProperty 'Value' for my usercontrol. Whenever combobox selection was changed, I will update the 'Value' property and also when 'Value' property is update I will update combobox. But I found the problem when I use my usercontrol in MVVM. I bind the 'Value' property with my IsEnable property in my viewModel. I set binding mode as TwoWay binding. But when I changed selection in comboBox, IsEnable property is never set.

These are some part of code

My usercontrol

public bool Value
    {
        get { return (bool)GetValue(ValueProperty); }
        set { SetValue(ValueProperty, value); }
    }
public static readonly DependencyProperty ValueProperty =
        DependencyProperty.Register("Value", typeof(bool), 
        typeof(BooleanComboBox),
        new UIPropertyMetadata(true, OnValuePropertyChanged));

private void Cmb_Selection_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ComboBox cmb = sender as ComboBox;
        object selectedValue = cmb.SelectedValue;
        if (selectedValue == null)
        {
            this.Value = false;
        }
        else
        {
            if (selectedValue.GetType() == typeof(bool))
            {
                this.Value = (bool)selectedValue;
            }
            else
            {
                this.Value = false;
            }
        }

        if (this.OnValueChange != null)
            this.OnValueChange(this, this.Value);
    }
private static void OnValuePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
    {
        BooleanComboBox self = sender as BooleanComboBox;
        self.Cmb_Selection.SelectedValue = (bool)args.NewValue;
    }

In window, where I place my usercontrol. ( I already set usercontrol's datacontext to my viewModel)

<tibsExtControl:BooleanComboBox Grid.Row="4" Grid.Column="1" 
                                            VerticalAlignment="Center"
                                            Value="{Binding Path=NewTemporaryZone.IsEnable, 
                                                            Mode=TwoWay, 
                                                            UpdateSourceTrigger=PropertyChanged}"
                                            x:Name="Cmb_AllowNonLBILogon"/>

In my model class I declare an IsEnable property

private bool _isEnable;
public bool IsEnable
{
    get { return _isEnable; }
    set 
    { 
        _isEnable= value;
        OnPropertyChanged("IsEnable");
    }
}

What's going on with my usercontrol. I miss something ? Please help me. T.T

A: 

Please check whether you have any binding error in the output window of VS.

Avatar
A: 

Try refreshing your binding in Cmb_Selection_SelectionChanged. Something like:

BindingExpression b = cmb.GetBindingExpression(MyNamespace.ValueProperty);
b.UpdateSource();
Rachel