查找在单个步骤中将 XAML 菜单项属性复制到按钮的某种方法



假设我有多个这样的菜单项:

<MenuItem Name="MenuItemDownload" Command="{Binding DownloadCommand}"
Header="Download"
ToolTip="Some long description of whats happening...">
<MenuItem.Icon>
<Image Source="/Resources/download.png"
Width="{Binding Source.PixelWidth, RelativeSource={RelativeSource self}}" />
</MenuItem.Icon>
</MenuItem>

对于其中一些菜单项,我有工具栏按钮,目前定义如下:

<Button Command="{Binding DownloadCommand}"
ToolTip="{Binding ElementName=MenuItemDownload, Path=ToolTip}">
<Image Source="{Binding ElementName=MenuItemDownload, Path=Icon.Source}"
Width="{Binding Source.PixelWidth, RelativeSource={RelativeSource self}}" />
</Button>

这行得通。我可以定义所有内容一次并将其传输到按钮。但我正在寻找类似"这是菜单项是您的参考元素"之类的东西。复制/绑定定义并与您相关的所有内容"... 类似的东西

<Button IsMirroring="{Binding ElementName=MenuItemDownload}" />

我相信这是可能的...但是怎么做呢?请给我一些关键字或提示:)

以下解决方案与您的IsMirroring="{Binding ElementName=MenuItemDownload}"想法保持接近。创建附加属性并在代码隐藏中初始化绑定:

public static class Attached
{
public static MenuItem GetMirrorSource(DependencyObject obj)
{
return (MenuItem)obj.GetValue(MirrorSourceProperty);
}
public static void SetMirrorSource(DependencyObject obj, MenuItem value)
{
obj.SetValue(MirrorSourceProperty, value);
}
// Using a DependencyProperty as the backing store for MirrorSource.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty MirrorSourceProperty =
DependencyProperty.RegisterAttached("MirrorSource", typeof(MenuItem), typeof(Attached), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(OnMirrorSourceChanged)));
private static void OnMirrorSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var button = d as Button;
if (button != null)
{
// initialize bindings and content image
button.SetBinding(Button.CommandProperty, new Binding("Command") { Source = e.NewValue });
button.SetBinding(Button.ToolTipProperty, new Binding("ToolTip") { Source = e.NewValue });
var content = button.Content as Image;
if (content == null)
{
content = new Image();
content.Stretch = Stretch.None;
button.Content = content;
}
content.SetBinding(Image.SourceProperty, new Binding("Icon.Source") { Source = e.NewValue });
}
}
}

命名空间声明的用法xmlns:local=...

<Button local:Attached.MirrorSource="{Binding ElementName=MenuItemDownload}"/>

只要按钮静态分配给菜单项,这就足够了。如果镜像按钮发生大量更改,则最好避免为每次更改创建新绑定。

请注意,我选择了Image.Stretch = Stretch.None而不是绑定宽度,因为我认为这是您的实际意图 - 可能是错误的。

最新更新