【问题标题】:Reusing WPF UserControls in MainWindow在 MainWindow 中重用 WPF 用户控件
【发布时间】:2017-03-07 05:27:38
【问题描述】:

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

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

为了从 MainWindow.xaml 设置 Image,我在 UserControl 代码中创建了一个 DependencyProperty,这将允许我设置 Image File 属性。

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>

我被困在这个状态。如何使 MainWindow.xaml 可以使用此依赖项属性(用户控件)?

【问题讨论】:

标签: c# wpf image xaml user-controls


【解决方案1】:

此属性是只读的依赖属性。对于这个属性,您需要 CLR 包装器,即

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

【讨论】:

  • 我应该将它包含在我的 UserControl 类中吗?
  • 是的..您需要将其包含在依赖属性为的类中,即当前上下文中的用户控件。
  • 如何从 MainWindow.xaml 访问此属性,如果我引用此属性,我会收到“无法访问或无法识别成员”错误
  • 现在应该可以访问了..尝试构建一次。
  • 另外,您应该创建普通的依赖属性而不是附加属性,正如@Ash 在评论中提到的那样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-25
  • 1970-01-01
  • 1970-01-01
  • 2011-09-30
相关资源
最近更新 更多