好了,我在不同的文件中有了带有其样式的自定义控件和带有iccommand属性的视图模型。
CustomControl.cs
public class CustomButtons: Control
{
public static readonly DependencyProperty CmdExecProperty =
DependencyProperty.Register(nameof(CmdExec), typeof(bool), typeof(CustomButtons),
new PropertyMetadata(false, ValuePropertyChange));
public bool CmdExec
{
get => (bool)GetValue(CmdExecProperty);
set => SetValue(CmdExecProperty, value);
}
private static void ValuePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is CustomButtons self)
{
DataViewModel dataViewModel = (DataViewModel)self.DataContext;
if (self.CmdExec)
{
dataViewModel.ExecuteCommand.Execute(dataViewModel.ExecuteCommand);
}
}
}
}
CustomButtonsStyle.xaml
</ResourceDictionary.MergedDictionaries>
<!-- Control template for a CustomButtons -->
<ControlTemplate x:Key="CustomButtonsTemplate"
TargetType="{x:Type v:CustomButtons}">
<Grid Width="128"
d:DesignHeight="200">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition MaxHeight="52" />
</Grid.RowDefinitions>
<Button x:Name="LoadButton"
Grid.Row="1"
Height="50"
HorizontalAlignment="Stretch"
Command="{Binding ExecuteCommand}"
CommandParameter="{Binding Path=Critical,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type v:CustomButtons}},
Mode=OneWay}"
Content="CmndExec"
IsEnabled="true" />
</Button>
</Grid>
</ControlTemplate>
<Style x:Key="CustomButtonsStyle"
TargetType="{x:Type v:CustomButtons}">
<Setter Property="Template" Value="{StaticResource CustomButtonsTemplate}" />
</Style>
<Style TargetType="{x:Type v:CustomButtons}" BasedOn="{StaticResource CustomButtonsStyle}" />
</ResourceDictionary>
DataViewModel.cs命令在文件中。
private ICommand _executeCommand;
public ICommand ExecuteCommand
{
get
{
return _executeCommand
?? (_executeCommand = new DelegateCommand<string>(ExecuteCommandMethod));
}
}
使用
<kit:CustomButtons x:Name="Buttons"
CmdExec="True"/>
这个CustomControl工作得很好,但我想当CmdExec dependencyproperty为True时,命令即ExecuteCommand(命令名)在CustomButtonsStyle中使用。无论按钮是否被按下,xaml (Button)都应该执行。
现在命令与按钮完美绑定,当我按下按钮时,它工作得很好。
但问题是,假设CmdExec="True",那么不管按钮是否按下,命令应该完成它的工作。我试着在CustomButton.cs中的ValueChangeProperty中这样做,但是,我仍然无法实现这一点。
任何帮助如何解决这个问题,当CmdExec为true时,ExecuteCommand ICommand属性应该执行。
private static void ValuePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is CustomButtons self &&
(bool) e.NewValue &&
self.DataContext is DataViewModel dataViewModel)
{
dataViewModel.ExecuteCommand.Execute(self.Critical);
}
}
注:没有完整的代码,但是根据所示的XAML,最好这样声明命令参数绑定:
<Button x:Name="LoadButton"
Grid.Row="1"
Height="50"
HorizontalAlignment="Stretch"
Command="{Binding ExecuteCommand}"
CommandParameter="{TemplateBinding Critical}"
Content="CmndExec"
IsEnabled="true" />