【问题标题】:Binding xaml property visibility to ViewModel, control with button将 xaml 属性可见性绑定到 ViewModel,使用按钮进行控制
【发布时间】:2017-10-05 03:38:17
【问题描述】:

我在 xmal 中有一个 StackLayout 属性,如下所示:

   <StackLayout x:Name="_infoView"
                 Margin="0,10,0,10"
                 BackgroundColor="Black"
                 IsVisible="{Binding State}"/>

以及 ViewModel 中的绑定 bool 变量

    private Boolean _state = true;
    public Boolean State
    {
        get { return _state; }
        set { }
    }

我的 xmal 中有一个按钮,想控制 StackLayout 的可见性,所以我做了这样的事情:

        <Button x:Name="CloseButton"
                Grid.Row="0"
                Grid.Column="3"
                Command="{Binding CloseWindowCommand}"/>

在 ViewModel 中

CloseWindowCommand = new Command(CloseWindowTapped, CanCloseWindowTapped);

public ICommand CloseWindowCommand { get; set; }
public void CloseWindowTapped()
{
     State = false;
}
public bool CanCloseWindowTapped()
{
    return true;
}

我假设,通过点击 CloseButton,我的 StackLayout 会消失...但它不起作用

【问题讨论】:

    标签: c# xaml mvvm data-binding


    【解决方案1】:

    ViewModel 应该实现 INotifyPropertyChanged 接口,用于通知 View 有关更改。

    public class ViewModel : INotifyPropertyChanged
    {
        // Implementing INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;
    
        protected void RaisePropertyChanged([CallerMemberName]string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName);
        }        
    
        // In the setter of property raise event to inform view about changes
        private Boolean _state = true;
        public Boolean State
        {
            get 
            { 
                return _state; 
            }
            set 
            { 
                _state = value;
                RaisePropertyChanged();
            }
        }
    }
    

    【讨论】:

    • 感谢您简单直接的回答!我还在了解 MVVM 模型,这很有帮助!
    猜你喜欢
    • 2010-09-27
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 2017-01-18
    • 1970-01-01
    • 1970-01-01
    • 2011-03-01
    • 2011-01-19
    相关资源
    最近更新 更多