C
C#2w ago
Elio

Access dependency property from a viewmodel WPF

HI, i'm using WPF and MVVM pattern. i've created a DependencyProperty IsEditable and how do i access this one from my viewmodel to bind it to CanExecute for my command.
public class ListingUserControl : UserControl
{
#region Properties
public bool IsEditable
{
get => (bool)GetValue(IsEditableProperty);
set => SetValue(IsEditableProperty, value);
}

public static readonly DependencyProperty IsEditableProperty =
DependencyProperty.Register(
"IsEditable",
typeof(bool),
typeof(ListingUserControl),
new PropertyMetadata(true));
#endregion

}
public class ListingUserControl : UserControl
{
#region Properties
public bool IsEditable
{
get => (bool)GetValue(IsEditableProperty);
set => SetValue(IsEditableProperty, value);
}

public static readonly DependencyProperty IsEditableProperty =
DependencyProperty.Register(
"IsEditable",
typeof(bool),
typeof(ListingUserControl),
new PropertyMetadata(true));
#endregion

}
private bool CanExecuteCommand() { return IsEditable; }
private bool CanExecuteCommand() { return IsEditable; }
2 Replies
Denis
Denis2w ago
Dependency props are part of the view and shouldn't touch the viewmodel Bind the dependency property to the control that invokes the command, use it as a toggle for the control's IsEnabled, visibility or whatever. Alternatively, pass the dependency property as the command parameter Bind to the dependency property via template binding
Elio
Elio2w ago
ohhhh true i've understand i bind IsEditable to isEnabled in the control for exemple :
<Button
HorizontalAlignment="Center"
VerticalAlignment="Center"
Background="{StaticResource ButtonGradientPrimaryColor}"
Command="{Binding Path=DataContext.RemoveCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}"
IsEnabled="{Binding IsEditable}"
CommandParameter="{Binding Path=SelectedItems, ElementName=DataGridThickness}"
Style="{StaticResource PrimaryButtonStyle20x20}">
<Image Source="{StaticResource ICON_DEL_20x20}" />
</Button>
<Button
HorizontalAlignment="Center"
VerticalAlignment="Center"
Background="{StaticResource ButtonGradientPrimaryColor}"
Command="{Binding Path=DataContext.RemoveCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}"
IsEnabled="{Binding IsEditable}"
CommandParameter="{Binding Path=SelectedItems, ElementName=DataGridThickness}"
Style="{StaticResource PrimaryButtonStyle20x20}">
<Image Source="{StaticResource ICON_DEL_20x20}" />
</Button>