我需要一個自定義控件(CC),CC中的文本框的Text屬性可以綁定到CC上的DependancyProperty。將Textbox.Text綁定到自定義控件DP
我也嘗試將textbox.text與templatebinding綁定。
我嘗試了幾乎所有我能想到的事情,該怎麼辦? :
自定義控制在泛型:
<Style TargetType="{x:Type local:TextboxCC}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:TextboxCC}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<TextBox Text="{Binding NText, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:TextboxCC}}}" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
CC.cs
public class TextboxCC : Control
{
public string NText
{
get { return (string)GetValue(NTextProperty); }
set { SetValue(NTextProperty, value); }
}
// Using a DependencyProperty as the backing store for NText. This enables animation, styling, binding, etc...
public static readonly DependencyProperty NTextProperty =
DependencyProperty.Register("NText", typeof(string), typeof(TextboxCC), new PropertyMetadata(null));
static TextboxCC()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(TextboxCC), new FrameworkPropertyMetadata(typeof(TextboxCC)));
}
}
主窗口:
標籤是隻是爲了檢查,如果該值在Mainwindow.Test
改變<local:TextboxCC NText="{Binding Test,Mode=TwoWay}" HorizontalAlignment="Left" Margin="115,99,0,0" VerticalAlignment="Top" Width="206"/>
<Label Content="{Binding Test,Mode=TwoWay}" HorizontalAlignment="Left" Margin="115,161,0,0" VerticalAlignment="Top" Width="206"/>
個Mainwindow.cs
public partial class MainWindow : Window, INotifyPropertyChanged
{
private string _test;
public string Test
{
get { return _test; }
set
{
_test = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Test"));
}
}
public MainWindow()
{
InitializeComponent();this.DataContext = this;
}
public event PropertyChangedEventHandler PropertyChanged;
}
你在設置DataContext嗎? – safetyOtter
是的,我在設計中做到了,但現在我在代碼中添加了它。 –
你的問題到底是什麼?你的代碼適合我。您是否需要在CC TextBox中的每個關鍵筆畫上更新綁定? – Clemens