WPF:使用自定义行为绑定到类的属性
问题描述:
使用WPF,c#,VS 2012WPF:使用自定义行为绑定到类的属性
尝试使用WPF实现UI的一些自定义行为。 目前创建从Behavior<FrameworkElement>
理念继承类:创建用于输入名字UI一个区域(我用的textBox) - 另一个区域(矩形) - 请参见与分组字段数据有所行动。
做了什么:
类实现的想法(类行为)
class SayHello: Behavior<FrameworkElement>
{
public string Words { get; set; }
protected override void OnAttached()
{
AssociatedObject.MouseLeftButtonUp += OnMouseClick;
}
private void OnMouseClick(object sender,
System.Windows.Input.MouseButtonEventArgs e)
{
MessageBox.Show(string.Format("hello , {0}", Words));
}
protected override void OnDetaching()
{
AssociatedObject.MouseLeftButtonUp -= OnMouseClick;
}
}
XAML:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
xmlns:local="clr-namespace:CH08.MovingCircle"
x:Class="CH08.MovingCircle.MainWindow"
Title="MainWindow" Height="350" Width="525">
<Canvas>
<Border Canvas.Top="220" BorderBrush="Black"
BorderThickness="2">
<TextBox x:Name="_enteredWords" Width="200"/>
</Border>
<Rectangle Stroke="Blue" Canvas.Top="250" Fill="Aquamarine"
Width="200" Height="50">
<i:Interaction.Behaviors>
<local:SayHello
Words="{Binding Text, ElementName=_enteredWords}"/>
</i:Interaction.Behaviors>
</Rectangle>
</Canvas>
遇到错误:A 'Binding' cannot be set on the 'Words' property of type 'SayHello'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject...
如果我改变XAML的一部分
<Rectangle Stroke="Blue" Canvas.Top="250" Fill="Aquamarine"
Width="200" Height="50">
<i:Interaction.Behaviors>
<local:SayHello
Words="Adbracadabra"/>
</i:Interaction.Behaviors>
</Rectangle>
- 所有作品(意思只是删除绑定)。
问题:是否可以创建绑定到具有自定义行为的类的属性?如果是的话,我该怎么做?
编辑:
正如由vfabre建议 - 改变属性依赖属性
public string Words
{
get { return (string)GetValue(WordsProperty); }
set { SetValue(WordsProperty, value); }
}
// Using a DependencyProperty as the backing store for Words.
//This enables animation, styling, binding, etc...
public static DependencyProperty WordsProperty =
DependencyProperty.Register("Words", typeof(string),
typeof(SayHello), new PropertyMetadata(default(string)));
结果
答
也许错误信息给我们的解决方案。你有你的财产Words
转换成以下的依赖属性为一个例子:
public string Words
{
get { return (string)GetValue(WordsProperty); }
set { SetValue(WordsProperty, value); }
}
// Using a DependencyProperty as the backing store for Words. This enables animation, styling, binding, etc...
public static readonly DependencyProperty WordsProperty =
DependencyProperty.Register("Words", typeof(string), typeof(SayHello), new PropertyMetadata(default(string)));
//public string Words { get; set; }
我建议你使用的代码snnipet propdp
。请致电propdp
,然后tab+tab
。
Here你可以找到更多关于依赖属性的信息。
问候
编辑 改变从字符串的默认值。
尝试它,现在与绑定 - 好的,但有另一个问题与默认值 - 类型不匹配,解决 - http://*.com/q/20398751/2012219。现在是工作,请看我的编辑 – gbk