使用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)));
結果
嘗試它,現在與綁定 - 好的,但有另一個問題與默認值 - 類型不匹配,解決 - http://stackoverflow.com/q/20398751/2012219。現在是工作,請看我的編輯 – gbk