How to disable textblock with mvvm?
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;
}
but this doesn't do nothing
You need to set the datacontext in your code behind:
public partial class MainWindow : Window
{
public MainWindow ()
{
InitializeComponent();
this.DataContext = new ViewModel();
}
}
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>
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));
}
}
The INotifyPropertyChange "updates" your UI if the value of your model changes.
Heyho,
you should implement INotifyPropertyChanged
like the following example:
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
}
Regards,
k1ll3r8e