【发布时间】:2021-11-27 22:16:22
【问题描述】:
好的,我在不同的文件中有自定义控件及其样式和具有 ICommand 属性的视图模型。
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 DepenencyProperty 为 True 时,无论是否按下按钮,都应执行命令,即 ExecuteCommand(命令名称用于按钮下的 CustomButtonsStyle.xaml)。
现在命令与按钮完美绑定,当我按下按钮时,它工作正常。
但问题是,假设 CmdExec="True",那么无论是否按下按钮都无关紧要,命令应该完成它的工作。 我尝试在 CustomButton.cs 的 ValueChangeProperty 中执行此操作,但仍然无法实现。
任何帮助如何解决此问题,当 CmdExec 为 true 时,应执行 ExecuteCommand ICommand 属性。
【问题讨论】:
标签: c# wpf xaml dependency-properties icommand