Eri*_*ith 2 c# wpf user-controls dependencies properties
我创建了一个UserControl,它本质上是一个按钮.它上面有一个Image和一个Label,我创建了两个属性来设置Image的源和Label的文本,如下所示:
public ImageSource Icon
{
get { return (ImageSource)this.GetValue(IconProperty); }
set { this.SetValue(IconProperty, value); icon.Source = value; }
}
public static readonly DependencyProperty IconProperty = DependencyProperty.Register("Icon", typeof(ImageSource), typeof(NavigationButton));
public string Text
{
get { return (string)this.GetValue(TextProperty); }
set { this.SetValue(TextProperty, value); label.Content = value; }
}
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(NavigationButton));
Run Code Online (Sandbox Code Playgroud)
但是,当我将控件添加到我的页面时,控件不会响应我在XAML中设置的任何属性,例如<controls:MusicButton Icon="/SuCo;component/Resources/settings.png/>什么都不做.
我究竟做错了什么?
CLR性能那套依赖属性应该永远比调用其他任何逻辑GetValue和SetValue.那是因为他们甚至可能都没有被召唤.例如,XAML编译器将通过调用GetValue/ SetValue直接而不是使用您的CLR属性进行优化.
如果在更改依赖项属性时需要执行某些逻辑,请使用元数据:
public ImageSource Icon
{
get { return (ImageSource)this.GetValue(IconProperty); }
set { this.SetValue(IconProperty, value); }
}
public static readonly DependencyProperty IconProperty = DependencyProperty.Register("Icon", typeof(ImageSource), typeof(NavigationButton), new FrameworkPropertyMetadata(OnIconChanged));
private static void OnIconChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
//do whatever you want here - the first parameter is your DependencyObject
}
Run Code Online (Sandbox Code Playgroud)
编辑
在我的第一个答案中,我假设你的控件的XAML(无论是从模板还是直接在UserControl中)都正确地连接到属性.你还没有向我们展示XAML,所以这可能是一个不正确的假设.我希望看到类似的东西:
<StackPanel>
<Image Source="{Binding Icon}"/>
<TextBlock Text="{Binding Text}"/>
</StackPanel>
Run Code Online (Sandbox Code Playgroud)
并且 - 重要的是 - 您的DataContext必须设置为控件本身.您可以通过各种不同的方式执行此操作,但这是一个从后面的代码设置它的一个非常简单的示例:
public YourControl()
{
InitializeComponent();
//bindings without an explicit source will look at their DataContext, which is this control
DataContext = this;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3524 次 |
| 最近记录: |