1
我有一个简单的自定义控件,我有一个ControlTemplate
为。我似乎无法从控制台上的Button
获取命令,以便路由至其TemplatedParent
的命令。路由命令模板父
<Style x:Key="SaveButtonStyle" TargetType="{x:Type Controls:SaveButton}">
<Style.Resources>
<converters:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter"/>
</Style.Resources>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Controls:SaveButton}">
<DockPanel Width="65" Height="21" LastChildFill="True">
<Canvas DockPanel.Dock="Left" HorizontalAlignment="Right" Margin="0 0 -49 0" ZIndex="1" IsHitTestVisible="False" >
<Image Source="Images/green-check.png" Width="16" Height="16" Visibility="{Binding IsDirty, Converter={StaticResource BoolToVisibilityConverter}}" Canvas.Top="-3" RenderOptions.BitmapScalingMode="Fant" />
</Canvas>
<Button DockPanel.Dock="Left" HorizontalAlignment="Left" Width="40" Height="21" FontSize="10"
Content="{Binding SaveButton.Content, RelativeSource={RelativeSource TemplatedParent}, FallbackValue={x:Static Localization:Strings.Save}}"
Command="{Binding SaveButton.Command, RelativeSource={RelativeSource TemplatedParent}}"
CommandParameter="{Binding SaveButton.CommandParameter, RelativeSource={RelativeSource TemplatedParent}}" />
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
这:
public class SaveButton : Button {
public static readonly DependencyProperty IsDirtyProperty = DependencyProperty.Register("IsDirty", typeof(bool), typeof(SaveButton));
static SaveButton() {
DefaultStyleKeyProperty.OverrideMetadata(typeof(SaveButton), new FrameworkPropertyMetadata(typeof(SaveButton)));
}
[Bindable(true), Category("Action")]
[Localizability(LocalizationCategory.NeverLocalize)]
public bool IsDirty {
get { return (bool)GetValue(IsDirtyProperty); }
set { SetValue(IsDirtyProperty, value); }
}
}
和(最后):
<Controls:SaveButton Command="{Binding Save}" IsDirty="{Binding IsDirty}" Style="{DynamicResource SaveButtonStyle}"/>
有趣的部分是,IsDirty
和Content
绑定似乎正常工作。这只是命令路由,似乎没有工作。
<按钮...命令= “{TemplateBinding命令}” CommandParameter = “{TemplateBinding CommandParameter}”/> 将是可取的,但该命令似乎没有在窗口的ViewModel中处理SaveButton。我可以看到(在snoop中)控件的DataContext实际上是Window的DataContext。它只是不调用ViewModel中的DelegateCommand。 public DelegateCommand
同意。我的首选是重新做按钮的视觉风格。我是一个新手,所以我不确定如何做到这一点,只需将该复选标记添加到按钮的右上角。如果你有这方面的建议,我愿意接受。 – Flea
@Flea它应该很简单,只需从模板中删除按钮,而不是Button放置一个ContentPresenter控件。所有应该工作,您的ContentPresenter将显示在按钮上设置的内容,并且您的SaveButton上的绑定设置的命令应该工作。 – jure