在UserControl上从样式资源设置ImageSource

时间:2016-08-03 20:55:01

标签: wpf data-binding

我创建了一个用户控件,其中一个图像组件内部绑定到DependencyProperty。一切都在运行时很好,但我无法在设计时看到图像。

ButtonBase.xaml:

<UserControl x:Class="VirtualEnvelopes.ButtonBase"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:VirtualEnvelopes"
         x:Name="ButtonRoot">
    <UserControl.Resources>
        <BitmapImage x:Key="DefaultImage" UriSource="/assets/common/nullButton.png" />
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot">
        <Grid>
            <Image x:Name="MainImageBitmap" Source="{Binding Path=MainImage, ElementName=ButtonRoot, TargetNullValue={StaticResource DefaultImage}}" Tag="{Binding Path=Tag, ElementName=ButtonRoot}" />
        </Grid>
    </Grid>
</UserControl>

ButtonBase.xaml.cs

public partial class ButtonBase : UserControl
{
    public static readonly DependencyProperty MainImageProperty =
        DependencyProperty.Register("MainImage", typeof(Uri), typeof(ButtonBase), new UIPropertyMetadata(null));

    public Uri MainImage
    {
        get { return (Uri)GetValue(MainImageProperty); }
        set { SetValue(MainImageProperty, value); }
    }

    public ButtonBase()
    {
        InitializeComponent();
    }
}

用法:

<Window x:Class="VirtualEnvelopes.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:base="clr-namespace:VirtualEnvelopes">
    <Window.Resources>
        <Style x:Key="Button1Style" TargetType="{x:Type base:ButtonBase}">
            <Setter Property="MainImage" Value="pack://application:,,,/pathToImage.png" />
        </Style>
    </Window.Resources>
    <Canvas Width="1000" Height="1000">
        <base:ButtonBase Style="{StaticResource Button1Style}" Tag="1" />
        <base:ButtonBase MainImage="pack://application:,,,/pathToImage.png" Tag="2" />
    </Canvas>
</Window>

两个按钮在运行时显示,但在设计空间中只能看到按钮#2。 Button1Style的setter中的值行带有下划线,表示不支持#34;指定的方法&#34;。

我已尝试将图片素材资源作为内容和资源,但它似乎没有任何区别。如何在设计时和运行时显示此图像?最终会有很多这些按钮,我需要在设计时将它们专门布置在画布上。

任何帮助都将不胜感激。

0 个答案:

没有答案