[英]Dependency Property Binding Not Updating Target
我有一個自定義的依賴項屬性:
public static readonly DependencyProperty HeaderProperty = DependencyProperty.Register("HeaderProperty", typeof(string), typeof(RadAdjustableSlider));
public string Header
{
get
{
return (string)GetValue(HeaderProperty);
}
set
{
SetValue(HeaderProperty, value);
}
}
然后,我的xaml中有一個綁定:
<TextBlock Name="txtHeader" Text="{Binding ElementName=main, Path=Header, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}" />
請注意,我在xaml文件頂部的聲明中也有此命令:
x:Name="main"
最后,我有這個構造函數:
public RadAdjustableSlider()
{
InitializeComponent();
this.Header = "Header";
}
當我將此控件放在另一個父控件中時,Header文本塊為空白。 為什么?
編輯: 此博客說正確的方法是通過在DependencyProperty.Register
調用中提供ValidateValueCallback ,但這似乎很麻煩,並且不能解釋與外部控件交互時依賴項屬性的行為。 我真的必須為所有依賴項屬性編寫回調函數嗎?
框架中已經有一個HeaderedContentControl和HeaderedItemsControl ...
但是,如果您真的想創建自己的,則應該使用TemplateBinding。 嘗試這樣的事情:
class MyHeaderedControl : ContentControl
{
public static readonly DependencyProperty HeaderProperty = DependencyProperty.Register(
"Header",
typeof(object),
typeof(MyHeaderedControl),
new PropertyMetadata());
public MyHeaderedControl()
{
this.DefaultStyleKey = typeof(MyHeaderedControl);
}
}
然后在您的項目中,在“ \\ Themes \\ Generic.xaml”中創建一個文件。 這是一個特別命名的文件,必須位於項目的根目錄中,然后位於主題文件夾中。 它必須包含一個ResourceDictionary。
<ResourceDictionary
xmlns="..."
xmlns:x="..."
xmlns:c="MyControlLibrary1"
>
<Style TargetType="{x:Type c:MyHeaderedControl>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type c:MyHeaderedControl}">
<StackPanel>
<ContentControl Content="{TemplateBinding Header}" />
<ContentPresenter />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
另外,如果尚不存在此屬性,請在AssemblyInfo.cs中添加該屬性:
[assembly: ThemeInfo(ResourceDictionaryLocation.SourceAssembly,
ResourceDictionaryLocation.SourceAssembly)]
因此,概述。 一般的想法是在您具有屬性,事件和邏輯等的地方創建某種類型的邏輯控件。然后在同一程序集中提供默認主題。 這就是默認情況下控件的顯示方式。 在使用控件的任何地方,都可以覆蓋默認模板,並且可以照常覆蓋特定模板。
因此,這是最輕松的方式,您可以將這樣的自定義內容添加到自定義控件中! 嘗試一次,這將是有意義的,不會讓人感到笨拙。 如果要進行更多控制,只需將其添加到Generic.xaml文件中即可。
就像上面提到的justin.m.chase一樣,自定義控件可能是最好的選擇,但是UserControls是常見的情況,因此無論如何我都會添加2c。
UserControl不會為您設置DataContent屬性,因此您在UserControl XAML中的所有綁定都解析為放置控件的DataContent。
若要更改此行為,請在usercontrol構造函數中設置DataContext屬性:
public RadAdjustableSlider()
{
InitializeComponent();
this.Header = "Header";
this.DataContext = this;
}
然后像這樣綁定:
<TextBlock Text="{Binding Header}" />
或不設置DataContext並像這樣綁定:
<TextBlock Text="{Binding Header, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ns:RadAdjustableSlider}}}" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.