【问题标题】:How to define default image in wpf usercontrol library如何在 wpf 用户控件库中定义默认图像
【发布时间】:2016-01-29 18:07:56
【问题描述】:

我用我的自定义用户控件创建了一个 wpf 用户控件库,以便在不同的项目中使用它们。

我有一个带有默认图像的按钮,但我希​​望能够在需要时更改按钮的图像:

public static readonly DependencyProperty BTN_SEARCH_IMAGE =
    DependencyProperty.Register("ButtonImage", typeof (string), typeof (Searchbar));

我的属性包装器:

   public string ButtonImage
    {
        get
        {
            var strToCheck = GetValue(BTN_SEARCH_IMAGE) as string;
            return String.IsNullOrWhiteSpace(strToCheck)
                ? @"WPF_Controls;Component/Images/Search.png"
                : strToCheck;
        }
        set { SetValue(BTN_SEARCH_IMAGE, value); }
    }

在 XAML 中:

    <UserControl x:Class="WPF_Controls.Searchbar"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 Name="SearchBar">
        <DockPanel DataContext="{Binding ElementName=SearchBar}">
        <Button Name="btnSearch"
                DockPanel.Dock="Left"
                Command="{Binding Path=SearchCommand}">
            <Image Source="{Binding Path=ButtonImage}" />
        </Button>
    </DockPanel>
</UserControl>

如果用户没有将任何内容绑定到 ButtonImage,则应显示默认图像,否则用户可以选择。

【问题讨论】:

    标签: c# wpf user-controls


    【解决方案1】:

    您应该可以使用Style 执行此操作。如果您在整个应用程序可访问的某个地方定义该样式(例如 App.xaml),它将自动应用于所有 SearchBars。

    <Style TargetType="l:SearchBar">
        <Setter Property="ButtonImage" Value="TheImage" />
    </Style>
    

    SetterValue 可以绑定到StaticResource,或者您定义的图像。通常您会在ResourceDictionary 中执行此操作,您可以在其中将默认图像定义为StaticResource

    如果ButtonImage在图像上本地设置,它将覆盖样式设置的值。请参阅Dependency Property Value Precedence 以获取相关参考。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-14
      • 2016-05-18
      • 1970-01-01
      • 2011-05-16
      • 1970-01-01
      • 1970-01-01
      • 2019-03-20
      相关资源
      最近更新 更多