【发布时间】: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 可以使用此依赖项属性(用户控件)?
【问题讨论】:
-
不要制作附加的 DP,使用
DependencyProperty.Register并创建一个公共包装属性FileSelectImage(不需要 2 个静态 get/set 方法)。另见stackoverflow.com/documentation/wpf/2914/…
标签: c# wpf image xaml user-controls