C# 在主窗口中重用WPF用户控件
作为WPF的初学者,我正在尝试在WPF的MainWindow视图组件中多次使用不同属性的特定用户控件 UserControlFileSelect包含一个简单的布局,其中包含一个包含带有文本框字段的图像的按钮。在我的主窗体中,我计划多次使用此用户控件。i、 e.具有不同的图像 要从MainWindow.xaml设置图像,我在UserControl代码中创建了DependencyProperty,这将允许我设置图像文件属性C# 在主窗口中重用WPF用户控件,c#,wpf,image,xaml,user-controls,C#,Wpf,Image,Xaml,User Controls,作为WPF的初学者,我正在尝试在WPF的MainWindow视图组件中多次使用不同属性的特定用户控件 UserControlFileSelect包含一个简单的布局,其中包含一个包含带有文本框字段的图像的按钮。在我的主窗体中,我计划多次使用此用户控件。i、 e.具有不同的图像 要从MainWindow.xaml设置图像,我在UserControl代码中创建了DependencyProperty,这将允许我设置图像文件属性 public partial class FileSelectionVie
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?此属性是只读依赖项属性。您需要此属性的CLR包装器,即
public string FileSelectImage
{
get { return (string)GetValue(FileSelectImageProperty); }
set { SetValue(FileSelectImageProperty, value); }
}
不要创建附加的DP,使用
dependencProperty.Register
并创建一个公共包装属性FileSelectImage
(不需要两个静态get/set方法)。另请参见是否应将其包含在UserControl类中?是的。您需要将其包含在依赖项属性所在的类中,即当前上下文中的UserControl。如果引用此属性,则如何从MainWindow.xaml访问此属性errorIt现在应该可以访问。请尝试构建一次。此外,您应该创建普通的依赖项属性,而不是附加属性,如@Ash在注释中所述。