从父模板到样式的WPF绑定

时间:2016-03-31 02:42:56

标签: c# wpf xaml

信息

我有两节课。

Question课程包含:IEnumerable<Answer>答案和string理由。

Answer类包含:string AnswerType和bool JustificationRequired。

注意:我显示的问题代码最少。

问题

我正在使用WPF。为了使模块化,我们正在使用StylesDataTemplates我正在尝试将Question.xaml中的TextBox Visibility绑定到Answer {{1由JustificationRequired触发的AnswerRadio.xaml中的属性。

代码

问题:

Style

答案:

public class Question : IQuestion
{
    public IEnumerable<Answer> Answers;
    public string Justification;
}

Question.xaml:

class Answer : IAnswer
{
    public string AnswerType;
    public string JustificationRequired;
}

AnswerTypeSelector.xaml:

<ContentControl
    x:Name="AnswerControl"
    Style="{StaticResource AnswerTypeSelector}" />

<TextBox
    x:Name="txtJustification"
    Visibility="{Binding Path=Style, ElementName=AnswerControl, Converter={StaticResource BooleanToVisibilityCollapsedConverter}}"
    Text="{Binding Justification}" />

AnswerRadio.xaml:

<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="../Templates/AnswerRadio.xaml" />
</ResourceDictionary.MergedDictionaries>

<Style x:Key="AnswerTypeSelector" TargetType="ContentControl">
    <Style.Triggers>
        <DataTrigger Binding="{Binding AnswerType}" Value="RadioButton">
            <Setter Property="Template" Value="{StaticResource AnswerRadioControl}" />
        </DataTrigger>
    </Style.Triggers>
</Style>

1 个答案:

答案 0 :(得分:0)

找到答案。

与AnswerRadioItem Style类似,我们可以使用RelativeResource Ancestoral绑定并绑定到调用ContentControl,然后绑定到它的[Tag][1]属性。

AnswerRadio.xaml

<ControlTemplate x:Key="AnswerRadioControl" TargetType="ContentControl">
    <StackPanel>
        <ListBox
        x:Name="lstQuestionRadioItem"
        ItemContainerStyle="{StaticResource AnswerRadioItem}"
        ItemsSource="{Binding Answers}"
        SelectedItem="{Binding Path=Tag, RelativeSource={RelativeSource AncestorType=ContentControl, Mode=FindAncestor, AncestorLevel=1}}">
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel Orientation="Horizontal" />
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
        </ListBox>
    </StackPanel>
</ControlTemplate>

然后在Question.xaml中,我们可以更改TextBox Visibility以查看该ContentControl.Tag属性。

我们还需要确保存在FallbackValue,因为这不会在运行时触发绑定。

Question.xaml:

<TextBox
    x:Name="txtJustification"
    Visibility="{Binding Path=Tag.JustificationRequired, ElementName=AnswerControl, Converter={StaticResource BooleanToVisibilityCollapsedConverter}, FallbackValue=Collapsed}"
    Text="{Binding Justification}" />