我看到了一些解决您问题的方法。你永远不会知道你的Button 的父级到底是什么,所以绑定到Window、Page 等属性背后的代码将很难在没有太多硬编码的情况下完成。
方法 1
订阅Button 的Loaded 事件,在Button 模板中找到Image FindName 并从那里设置源。这也可以通过附加行为
来完成
Xaml
<Button Style="{DynamicResource ButtonStyle1}"
Loaded="Button_Loaded"
...>
背后的代码
private void Button_Loaded(object sender, RoutedEventArgs e)
{
Button button = sender as Button;
Image imgIcon2 = button.Template.FindName("imgIcon2", button) as Image;
Uri uri = new Uri("Resources/icon1.png", UriKind.Relative);
ImageSource imgSource = new BitmapImage(uri);
imgIcon2.Source = imgSource;
}
方法2
创建一个名为 ImageButton 的子类 Button,您可以在其中添加一个新属性 UriSource,您可以将其绑定到模板内。
<Style x:Key="ButtonStyle1" TargetType="{x:Type local:ImageButton}">
<!--...-->
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:ImageButton}">
<!--...-->
<Image x:Name="imgIcon2"
Source="{Binding RelativeSource={RelativeSource self},
Path=UriSource}"
.../>
<!--...-->
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
可以使用
<local:ImageButton Style="{DynamicResource ButtonStyle1}"
UriSource="Resources/icon1.png"
...>
另外,我认为您可以从 ControlTemplate 内部绑定到附加属性,但这似乎不起作用..