WPF元素绑定在XAML中无法工作

3
这应该是相当简单和直接的,但是当从资源中使用时,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>

我该怎样解决它?
2个回答

2
你应该使用 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}" />

没有检查,但可能有效


1

而且你可以使用 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}" />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接