在MainWindow中重用WPF UserControls

时间:2016-10-25 08:42:02

标签: c# wpf image xaml user-controls

作为WPF的初学者,我试图在WPF中的MainWindow视图组件中多次重用具有不同属性的特定用户控件

UserControl FileSelect 包含一个简单的布局,其中包含一个包含带有文本框字段的图像的按钮。在我的主表单中,我计划多次使用此用户控件。即有不同的图像。

fileselector

要从MainWindow.xaml设置图像,我在UserControl代码中创建了一个DependencyProperty,这将允许我设置图像文件属性。

public partial class FileSelectionView : UserControl
    {
        public string GetFileSelectImage(DependencyObject obj)
        {
            return (string)obj.GetValue(FileSelectImageProperty);
        }

        public void SetFileSelectImage(DependencyObject obj, string value)
        {
            obj.SetValue(FileSelectImageProperty, value);
        }

        // Using a DependencyProperty as the backing store for FileSelectImage.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty FileSelectImageProperty =
            DependencyProperty.RegisterAttached("FileSelectImage", typeof(string), typeof(FileSelectionView), new PropertyMetadata("flash.png", OnImageFileChanged));

        private static void OnImageFileChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (DesignerProperties.GetIsInDesignMode(d)) return;

            FileSelectionView fv = ((FileSelectionView)(FrameworkElement)d);
            if (fv != null)
            {
                Image tb = (Image)fv.imgButtonFileSelect;

                //Image tb = ((System.Windows.Controls.Image)(FrameworkElement)d);
                //var imageConverter = new ImageSourceConverter();
                if (tb != null)
                {
                    tb.Source = new BitmapImage(new Uri("Images\\" + (string)e.NewValue, UriKind.Relative));
                }
            }
        }

        public FileSelectionView()
        {
            InitializeComponent();
        }
    }

现在我公开了Image属性,我假设它可以通过MainWindow.xaml

设置
<StackPanel Orientation="Vertical" Grid.Column="0" Grid.ColumnSpan="2">
      <View:FileSelectionView FileSelectImage="image01.png"/>
      <View:FileSelectionView FileSelectImage="image02.png"/>
      .. so on
</StackPanel>

我陷入了这种状态。如何使这个依赖属性(usercontrol)可用于MainWindow.xaml?

1 个答案:

答案 0 :(得分:2)

此属性是readonly Dependency属性。你需要这个属性的CLR包装器,即

public string FileSelectImage
{
    get { return (string)GetValue(FileSelectImageProperty); }
    set { SetValue(FileSelectImageProperty, value); }
}