簡體   English   中英

在MainWindow中重用WPF UserControls

[英]Reusing WPF UserControls in MainWindow

作為WPF的初學者,我試圖使用不同的屬性多次重用WPF的MainWindow視圖組件中的特定用戶控件。

UserControl FileSelect包含一個簡單的布局,該布局包含一個按鈕,該按鈕包含帶有文本框字段的圖像。 在我的主要形式中,我計划多次使用此用戶控件。 即具有不同的圖像。

fileselector

要從MainWindow.xaml設置圖像 ,我已經在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?

此屬性是只讀的Dependency屬性。 您需要此屬性的CLR包裝器,即

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM