Setting a control property in a DataTemplate does not work properly

I have user control:

public class TestTextBox : TextBox { public TestTextBox() { Text = "ctor text"; } } 

And xaml that uses this control:

 <StackPanel Orientation="Vertical"> <!-- 1. Use TestTextBox directly --> <controls:TestTextBox Text="xaml text"/> <!-- 2. Use TestTextBox in DataTemplate --> <ItemsControl> <ItemsControl.ItemTemplate> <DataTemplate> <controls:TestTextBox Text="xaml text"/> </DataTemplate> </ItemsControl.ItemTemplate> <System:String>111</System:String> </ItemsControl> <StackPanel> 

As a result, TestTextBox.Text is different in this case - "xaml text" in the first case, "ctor text" in the second case.

Can someone explain why it works this way? I expect TestTextBox.Text to be "xaml text" in both cases.

+4
source share
3 answers

I think you need to understand the Priority of the value of the dependency property .

When using templates, the priority of values ​​for dependency properties is different.

+1
source

It seems that you are doing it wrong. In fact, this is not a TextBox display, since you did not specify a source. Or what you can do is something like

 <ItemsControl.Items> <TestTextBoxFet:TestTextBox Text="xaml text"/> </ItemsControl.Items> 
+1
source

I agree with gaurawerma.

The priority of the value set in the constructor is higher than that set in the data template. Therefore, you see the result as different in both cases.

http://social.msdn.microsoft.com/Forums/en/wpf/thread/a4e7ed36-9a8a-48ce-a5d5-00a49376669b

0
source

Source: https://habr.com/ru/post/1398595/


All Articles