This should be fairly simple and straightforward but element binding is not working in XAML when using it from resource. It is working fine when using it directly in XAML.
Resources:
<Window.Resources>
<StackPanel x:Key="panel">
<CheckBox x:Name="chkDefaultValue" Content="Default Value"
IsChecked="{Binding ElementName=txtDefaultValue, Path=Text.Length, Mode=OneWay}" />
<TextBox x:Name="txtDefaultValue"
Text="{Binding DefaultValue, Mode=TwoWay, ValidatesOnDataErrors=True}"
IsEnabled="{Binding ElementName=chkDefaultValue, Path=IsChecked}" />
</StackPanel>
</Window.Resources>
XAML:
<StackPanel>
<!-- BINDING NOT WORKING -->
<ContentControl Content="{StaticResource panel}" />
<!-- BINDING WORKING HERE -->
<CheckBox x:Name="chkDefaultValue" Content="Default Value"
IsChecked="{Binding ElementName=txtDefaultValue, Path=Text.Length, Mode=OneWay}" />
<TextBox x:Name="txtDefaultValue"
Text="{Binding DefaultValue, Mode=TwoWay, ValidatesOnDataErrors=True}"
IsEnabled="{Binding ElementName=chkDefaultValue, Path=IsChecked}" />
</StackPanel>
How could i fix it?
You should use DataTemplate
<Window.Resources>
<DataTemplate DataType="{x:Type ContentControl}" x:Key="panel">
<StackPanel>
<CheckBox x:Name="chkDefaultValue" Content="Default Value"
IsChecked="{Binding ElementName=txtDefaultValue, Path=Text.Length, Mode=OneWay}" />
<TextBox x:Name="txtDefaultValue"
Text="{Binding DefaultValue, Mode=TwoWay, ValidatesOnDataErrors=True}"
IsEnabled="{Binding ElementName=chkDefaultValue, Path=IsChecked}" />
</StackPanel>
</DataTemplate>
</Window.Resources>
and
<ContentControl ContentTemplate="{StaticResource panel}" />
didn't check, but probably works
And you can use ControlTemplate
<Window.Resources>
<ControlTemplate x:Key="panel">
<StackPanel>
<CheckBox x:Name="chkDefaultValue"
Content="Default Value"
IsChecked="{Binding ElementName=txtDefaultValue,
Path=Text.Length,
Mode=OneWay}" />
<TextBox x:Name="txtDefaultValue"
IsEnabled="{Binding ElementName=chkDefaultValue,
Path=IsChecked}"
Text="{Binding DefaultValue,
Mode=TwoWay,
ValidatesOnDataErrors=True}" />
</StackPanel>
</ControlTemplate>
</Window.Resources>
and
<ContentControl Template="{StaticResource panel}" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With