【问题标题】:How to bind a image source in ControlTemplate from Code behind?如何从后面的代码绑定 ControlTemplate 中的图像源?
【发布时间】:2011-02-03 19:34:43
【问题描述】:

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

图像在按钮样式的 ControlTemplate 中。我在多个 XAML 页面中实例化该 Button 样式。我的目标是在这些 xaml 页面后面的每个代码中定义“图标”实例,以放置每个 XAML 页面唯一的图标。或许,这可能是一种更好的方式来定义应该在每个将加载按钮样式的 XAML 页面中显示的唯一图标。

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

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

【问题讨论】:

    标签: wpf wpf-controls binding


    【解决方案1】:

    我看到了一些解决您问题的方法。你永远不会知道你的Button 的父级到底是什么,所以绑定到WindowPage 等属性背后的代码将很难在没有太多硬编码的情况下完成。

    方法 1

    订阅ButtonLoaded 事件,在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 内部绑定到附加属性,但这似乎不起作用..

    【讨论】:

    • 太棒了!非常感谢您的帮助。我会试试的。
    猜你喜欢
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多