问题描述
如何使用 mvvm 禁用文本块?
How to disable textblock with mvvm?
我是这个架构的新手,我尝试过 IsEnabled="{Binding IsEnable}"
,即:
I'm new with this architecture I tried with IsEnabled="{Binding IsEnable}"
, i.e:
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:
You need to set the datacontext in your code behind:
public partial class MainWindow : Window
{
public MainWindow ()
{
InitializeComponent();
this.DataContext = new ViewModel();
}
}
或者,在您的 XAML 中创建您的视图模型:
Or, alternatively, create your viewmodel in your XAML:
<Window x:Class="MainWindow"
...omitted some lines...
xmlns:ViewModel="clr-namespace:YourModel.YourNamespace">
<Window.DataContext>
<ViewModel:ViewModel />
</Window.DataContext>
<your page/>
</Window>
除此之外:我认为您希望您的页面对 ViewModel 中的更改做出反应.因此,您需要在视图模型中实现 INotifyPropertyChanged
,如下所示:
Besides that: I think you want your page to react to the changes in the ViewModel. Therefor you need to implement INotifyPropertyChanged
in your viewmodel, like this:
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.
The INotifyPropertyChange "updates" your UI if the value of your model changes.
这篇关于如何使用 mvvm 禁用文本块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!