WPF 元素绑定在 XAML 中不起作用

WPF Element Binding not working in XAML

这应该相当简单明了,但是从资源中使用它时,元素绑定在 XAML 中不起作用。在 XAML.

中直接使用它工作正常

资源:

<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>

我该如何解决?

你应该使用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>

<ContentControl ContentTemplate="{StaticResource panel}" />

没有检查,但可能有效

并且您可以使用 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>

<ContentControl Template="{StaticResource panel}" />