具有图像属性的WPF UserControl

时间:2019-04-29 10:50:55

标签: wpf image user-controls dependency-properties

我有一个UserControl库,其中包含一个为Windows创建自定义标题栏的用户控件。我给这个标题栏提供了两个依赖属性-Title和Icon,当我通过DLL使用控件时,我希望能够对其进行设置。

我已经使标题正常工作,因此,当我设置Window的ViewModel的Title属性时,它会填充到标题栏中。但是,我无法使图像执行相同的操作。

我尝试了各种变体,并阅读了有关使用依赖项属性的完整课程,但似乎无法显示图像。我已经尝试过使用ImageSource属性,Project Resources和Images,但是得到的只是空白。您能指出我正确的方向来解决此问题吗?

这里是用于用户控件的xaml(我读到我必须对DP使用TemplatedParent RelativeSource,所以将其放入-我相信这将引用实现中的MainViewModel):

<UserControl x:Class="WPFLibrary.User_Controls.TitleBar"
             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"
             mc:Ignorable="d">
    <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/WPFLibrary;component/Styles/Buttons.xaml"/>
                <ResourceDictionary Source="pack://application:,,,/WPFLibrary;component/Styles/Gradients.xaml"/>
                <ResourceDictionary Source="pack://application:,,,/WPFLibrary;component/Styles/Text.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </UserControl.Resources>
    <DockPanel VerticalAlignment="Top" Grid.Row="0" Grid.ColumnSpan="3"
               MouseDown="TitleBar_MouseDown"
               DataContext="{Binding}"
               Background="{StaticResource WindowTitleBar}">
        <Grid Grid.Row="0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="5"/>
                <ColumnDefinition Width="30"/>
                <ColumnDefinition Width="5"/>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="90"/>
            </Grid.ColumnDefinitions>
            <Image Grid.Column="1" Source="{Binding Icon,RelativeSource={RelativeSource TemplatedParent}}"/>
            <TextBlock x:Name="Title_Bar"
                       Grid.Column="3"
                       Text="{Binding Title}"
                       Style="{StaticResource Text_WindowTitle}">
            </TextBlock>
            <!--StackPanel Containing the buttons excluded for SO Question-->
        </Grid>
    </DockPanel>
</UserControl>

这是相同控件的代码(根据其他一些答案,我尝试将项目资源和ImageSource用于Image属性,但无济于事):

using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace WPFLibrary.User_Controls
{
    /// <summary>
    /// Interaction logic for TitleBar.xaml
    /// </summary>
    public partial class TitleBar : UserControl, INotifyPropertyChanged
    {

        public Image Icon
        {
            get { return (Image)GetValue(IconProperty); }
            set { SetValue(IconProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Icon.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IconProperty = DependencyProperty.Register("Icon", typeof(Image), typeof(TitleBar) );

        private static PropertyChangedEventArgs _stateChange = new PropertyChangedEventArgs("Windowstate");
        public WindowState _windowState;

        public WindowState Windowstate
        {
            get
            { return _windowState; }
            set
            {
                _windowState = value;
                NotifyChange(_stateChange);
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyChange(PropertyChangedEventArgs e)
        {
            PropertyChanged?.Invoke(this, e);
        }

        public TitleBar()
        {
            InitializeComponent();
        }

        //Button Click Methods excluded for SO question
    }
}

用于实现usercontrol的xaml是这样的-我将绑定设置为MainViewModel;具有用于设置属性的构造函数。

<Window x:Class="Demo_of_WPF_Library.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:uc="clr-namespace:WPFLibrary.User_Controls;assembly=WPFLibrary"
        xmlns:vm="clr-namespace:Demo_of_WPF_Library.ViewModel"
        mc:Ignorable="d"
        WindowStyle="None"
        BorderBrush="{StaticResource WindowBackgroundBrush}"
        x:Name="Main_Window"
        WindowState="{Binding Windowstate,ElementName=Titlebar}"
        Background="{StaticResource WindowBackgroundBrush}"
        Height="300" Width="800">
    <Window.DataContext>
        <vm:MainView_Model/>
    </Window.DataContext>
    <Grid>
        <uc:TitleBar Name="Titlebar" Icon="{Binding Icon}">
        </uc:TitleBar>
    </Grid>
</Window>

这是MainView_Model的代码,其中包含主窗口的属性:

namespace Demo_of_WPF_Library.ViewModel
{
    public class MainView_Model
    {
        private string _title;
        public string Title
        {
            get { return _title; }
            set { _title = value; }
        }
        private Image _icon;

        public Image Icon
        {
            get { return _icon; }
            set { _icon = value; }
        }

        public MainView_Model()
        {
            Title = "Demo WPF Library";
            Icon = new Image();
            Icon.Source = new BitmapImage(new Uri("/View/Images/IsItOk.ico",UriKind.Relative));
        }
    }
}

最后,这是mainwindow背后的代码,它设置对MainViewModel的绑定并初始化窗口:

public partial class MainWindow : Window
{
    public MainView_Model MainView { get; set; }
    public MainWindow()
    {
        MainView = new MainView_Model();
        DataContext = MainView;
        InitializeComponent();
    }
}

老实说,我看不到这里缺少什么/错了,我已经读了很多文章,问题和答案,基本上似乎在说我在以正确的方式做事……那么到底是什么呢?错误吗?

2 个答案:

答案 0 :(得分:4)

您的绑定错误。如果没有模板,则不应使用TemplatedParent。使用:

xmlns:local="clr-namespace:WPFLibrary.User_Controls"
<Image Grid.Column="1" Source="{Binding Icon, RelativeSource={RelativeSource AncestorType=local:TitleBar}}"/>

答案 1 :(得分:3)

问题是您的XAML中有一个试图绑定到视图模型中的Image的Image。像Image这样的GUI对象在视图模型层中没有位置,请将Icon依赖项属性更改为ImageSource类型,然后将XAML图像绑定到该类型。