admin管理员组文章数量:1122846
I have a content control with content control template which shows 2 controls in UI according to the content (as shown below).
I have DpValid dependency property in my usercontrol View1 & View2
<DataTemplate x:Key="MyT1Template">
<local:View1 DpValid="{Binding Path=Data.DpValid, Source={StaticResource Proxy1}}"/>
</DataTemplate>
<DataTemplate x:Key="MyT2Template">
<local:View2 DpValid="{Binding Path=Data.DpValid, Source={StaticResource Proxy1}}"/>
</DataTemplate>
<local:MyTemplateSelector x:Key="MyTemplateSelector"
T1Template="{StaticResource MyT1Template}"
T2Template="{StaticResource MyT2Template}" />
<Grid>
<ContentControl DockPanel.Dock="Top"
Content="{Binding SelectedPropertyView}"
ContentTemplateSelector="{StaticResource MyTemplateSelector}">
</ContentControl>
</Grid>
In my View1, I am using a treeview to show some data. I have 2 template selectors which the treeview should use according to DpValid
<local:DataItemTemplateSelector x:Key="DT1"
ListTemplate="{StaticResource ListTemplate}"
DefaultTemplate="{StaticResource DefaultTemplate}"/>
<local:DataItemTemplateSelector x:Key="DT2"
ListTemplate="{StaticResource ListTemplate}"
DefaultTemplate="{StaticResource AnotherTemplate}" />
public partial class View1: UserControl
{
public static readonly DependencyProperty DpValidProperty=
DependencyProperty.Register(nameof(DpValid), typeof(bool), typeof(View1), new PropertyMetadata(true, OnChanged));
public ListPropertiesView()
{
InitializeComponent();
}
public bool DpValid
{
get { return (bool)GetValue(DpValidProperty); }
set { SetValue(DpValidProperty, value); }
}
private static void OnChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is View1 control)
{
control.UpdateTemplateSelector();
}
}
private void UpdateTemplateSelector()
{
DataTemplateSelector ts = DpValid
? (DataTemplateSelector)Resources["DT1"]
: (DataTemplateSelector)Resources["DT2"];
treeview.ItemTemplateSelector = ts;
}
}
Its working. But I am getting some binding error when I switch from View1 to View2
HorizontalContentAlignment TreeViewItem.HorizontalContentAlignment HorizontalAlignment Cannot find source: RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1'.
But I am not setting these properties.
Another observation I made is that when the content control switches to View2, the Dependency Property value change is triggered with the default value, even though the bound property has not been modified.
It appears that during this value change, we attempt to set the ItemTemplateSelector
, which leads to a binding error since the UI is now in View2.
本文标签:
版权声明:本文标题:c# - Dependency property value change call back is invoked when a control hides from UI via content control template - Stack Ove 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736302965a1931722.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论