如何在CodeTehind中隐藏ControlTemplate中的图像源?

时间:2011-02-03 19:34:44

标签: wpf wpf-controls binding

我需要将代码中定义的图像源绑定到ControlTemplate中。我有问题使它正常工作。我想知道是否有人可以提供帮助。

图像位于Button样式的ControlTemplate中。我在多个XAML页面中实例化了Button样式。我的目标是在这些xaml页面后面的每个代码中定义“Icon”实例,以放置每个XAML页面唯一的图标。 Perphaps,它可以更好地定义应该在每个XAML页面中显示的加载按钮样式的唯一图标。

以下是我创建的解决方案的链接。这是一个简单的示例,其中我有2个xaml页面,按钮使用相同的样式。我需要能够在打开mainWindow.xaml时将icon1.png加载到按钮中,并在打开Page1.xaml时将icon2.png加载到icon2png。

http://cid-0c29483cf3a6a14d.office.live.com/self.aspx/WPF%5E_Tests/BindingImageFromCode.zip

1 个答案:

答案 0 :(得分:0)

我看到了几个问题的解决方案。你永远不会知道你的Button的父亲到底是什么,因此绑定到WindowPage的属性背后的代码将很难完成而不需要太多的硬编码。< / p>

方法1

订阅Loaded的{​​{1}}活动,在Button模板Image中找到Button,然后从那里设置来源。这也可以通过附加行为

来完成

Xaml

FindName

代码

<Button Style="{DynamicResource ButtonStyle1}"
        Loaded="Button_Loaded"
        ...>

方法2

创建一个名为eg 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; } 的子类Button,您可以在其中添加一个新属性ImageButton,您可以将其绑定到模板中。

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>

另外,我认为您可以从ControlTemplate内部绑定到附加属性,但这似乎不起作用..