我有两节课。
Question
课程包含:IEnumerable<Answer>
答案和string
理由。
Answer
类包含:string
AnswerType和bool
JustificationRequired。
注意:我显示的问题代码最少。
我正在使用WPF。为了使模块化,我们正在使用Styles
和DataTemplates
我正在尝试将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>
答案 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}" />