如何用mvvm禁用文本块?

时间:2018-04-21 11:20:16

标签: c# wpf xaml 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;
}

但这并不是什么

2 个答案:

答案 0 :(得分:1)

您需要在代码中设置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会“更新”您的用户界面。

答案 1 :(得分:1)

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