繁体   English   中英

如何用mvvm禁用文本块?

[英]How to disable textblock with mvvm?

如何用mvvm禁用文本块?

我是用IsEnabled="{Binding IsEnable}"尝试过的这种架构的新手,即:

XAML:

<TextBlock x:Name="version_textBlock" IsEnabled="{Binding IsEnable}" 
          Height="20" Margin="155,144,155,0" TextWrapping="Wrap"
          HorizontalAlignment="Center" Text="mylabel"  
          FontFamily="Moire ExtraBold"
          RenderTransformOrigin="0.582,0.605" Width="210" />

ViewModel.cs:

public bool IsEnable { get; set; }
//constarctor
public ViewModel()
{
  IsEnable = false;
}

但这并没有什么作用

您需要在代码中设置datacontext:

public partial class MainWindow : Window
{
    public MainWindow ()
    { 
        InitializeComponent();
        this.DataContext = new ViewModel();
    }
}

或者,或者,在XAML中创建viewmodel:

<Window  x:Class="MainWindow"
    ...omitted some lines...
    xmlns:ViewModel="clr-namespace:YourModel.YourNamespace">

    <Window.DataContext>
         <ViewModel:ViewModel />
     </Window.DataContext>

     <your page/>
</Window>

除此之外:我认为您希望您的页面对ViewModel中的更改做出反应。 因此,您需要在viewmodel中实现INotifyPropertyChanged ,如下所示:

public class ViewModel: INotifyPropertyChanged
{
    private string _isEnabled;
    public string IsEnabled
    {
        get { return _isEnabled; }
        set
        {
            if (value == _isEnabled) return;
            _isEnabled= value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
 }

如果模型的值发生更改,则INotifyPropertyChange会“更新”您的UI。

Heyho,您应该像以下示例一样实现INotifyPropertyChanged

public class ViewModel : INotifyPropertyChanged
{
    private bool _isEnabled;

    public bool IsEnabled
    {
        get
        {
            return _isEnabled;
        }
        set
        {
            if (_isEnabled != value)
            {
                _isEnabled = value;
                OnPropertyChanged("IsEnabled");
            }
        }
    }


    #region INotify

    #region PropertyChanged

    ///<summary>
    /// PropertyChanged event handler
    ///</summary>
    public event PropertyChangedEventHandler PropertyChanged;

    #endregion

    #region OnPropertyChanged

    ///<summary>
    /// Notify the UI for changes
    ///</summary>
    public void OnPropertyChanged(string propertyName)
    {
        if (string.IsNullOrEmpty(propertyName) == false)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    #endregion

    #endregion
}

问候,

k1ll3r8e

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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