开发者

MVVM property with a linked complex class and CanExecute Relay Command not working

开发者 https://www.devze.com 2023-01-26 16:55 出处:网络
I have a entity class in a C# library class and linked to Silverlight class library (entities must be in C# class because of legacy compatiblity with other systems)

I have a entity class in a C# library class and linked to Silverlight class library (entities must be in C# class because of legacy compatiblity with other systems)

Example (C# library):

public class TestClass
{        
    private string _testValue;
    public string TestValue
    {
        get { return _testValue; }
        set
        {
            if (_testValue!= value)
            {
                _testValue = value;
                OnPropertyChanged("TestValue");
            }
        }
    }}

This class is linked to Silverlight class library.

On a MVVM there is a property

private TestClass _testProp = new TestClass();
        public TestClass TestProp
  开发者_StackOverflow中文版      {
            get
            {
                return _testProp ;
            }
            set
            {
                if (value != _testProp )
                {
                    _testProp = value;
                    RaisePropertyChanged("TestProp");
                    PressCommand.CanExecuteChanged();
                }
            }
        }

The property is binded to a control in XAML

<TextBox Text="{Binding TestProp.TestValue, Mode=TwoWay}">
<Button Content="Press" Command="{Binding PressCommand}" />

I want to control the button with RelayCommands CanExecute depended on the TestValue in TestClass...

    PressCommand = new RelayCommand(() =>
    {
        DoSomething();
    }, () => TestProp.TestValue != string.empty);

However, if the TestValue in changed (different then empty string), PressCommand CanExecute doen't seem to notice the change and is not enabled, making it unusable...

Is it possible to use the CanExecute with this kind of set-tu


What you need to do is call PressCommand.CanExecuteChanged() when the value changes. To do this nicely listen for the property change of the value in the property

VM

 public TestClass TestProp
    {
        get
        {
            return _testProp ;
        }
        set
        {
            if (value != _testProp )
            {
                if(_testProp != null)
                {
                    _testProp.PropertyChanged -= TestPropChanged;
                }


                _testProp = value;

                if(_testProp != null)
                {
                    _testProp.PropertyChanged += TestPropChanged;
                }

                RaisePropertyChanged("TestProp");
                PressCommand.CanExecuteChanged();
            }
        }
    }

 private void TestPropChanged(object sender, PropertyChangedEventArgs e)
 {
      //Can check for specific property if required...

      PressCommand.CanExecuteChanged();
 }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号