【问题标题】:WPF - How to make RadioButtons generated by a DataTemplate be mutually exclusive?WPF - 如何使 DataTemplate 生成的 RadioButtons 互斥?
【发布时间】:2010-12-02 12:07:01
【问题描述】:

我正在构建的一个应用程序需要构建一个供用户进行的调查。与我的问题相关的相关课程是:

 Survey (string Description, List<Questions> Questions, QuestionTypes Type)
 Question (string Description, List<Choice> Choices)
 Choice (string Description)
 enum QuestionTypes {MultipleChoicesOneAnswer, MultipleChoicesMultipleAnswers}

在 ListBox 中,我想在自己的边框中显示每个问题以及每个问题的可用选项。像这样:
1) 一天有几个小时?
[ ] 21
[ ] 22
[ ] 23
[ ] 24

上面的括号代表一个单选按钮(如果问题类型是“MultipleChoicesOneAnswer”)或复选框(对于“MultipleChoicesMultipleAnswers”类型的问题)

我正在使用以下模板:

<DataTemplate x:Key="MultipleChoicesOneAnswerTemplate" DataType="{x:Type local:Choice}">
   <RadioButton Content="{Binding Description}" Foreground="Blue"  />
</DataTemplate>


<DataTemplate x:Key="QuestionTemplate" DataType="{x:Type local:Question}">
   <DockPanel>
      <StackPanel Orientation="Horizontal" DockPanel.Dock="Top">
         <TextBlock Text="{Binding SortingIndex}" />
         <TextBlock Text=")" />
         <TextBlock Text="{Binding Description}" Margin="5,0,0,0"/>
      </StackPanel>
      <ListBox ItemTemplate="{StaticResource MultipleChoicesOneAnswerTemplate}" ItemsSource="{Binding Choices}"/>
   </DockPanel>
</DataTemplate>

使用这些模板,我会为每个选择获得一个 RadioButton,但它们并不是每个问题都互斥的。

我的问题是:

1、如何使模板生成的RadioButtons互斥?
2. 我将如何将用户选择的选项记录到我的模型中?

非常感谢您的帮助。

更新: 按照 csunwold 的建议,它使用 GroupName 来工作,但感觉有点像 hack,因为我必须在 Question 类上重写 ToString() 并吐出描述并使用 GroupName="{Binding Question}"。

其他人有什么建议吗?

【问题讨论】:

    标签: wpf xaml listbox radio-button datatemplate


    【解决方案1】:

    给要相互排斥的单选按钮相同的 GroupName 属性。您可能会将此记录到您的模型中,但创建一个枚举类型,每次选中一个单选按钮时都会更新。

    【讨论】:

    • 如何从 DataTemplate 中获取 GroupName?谢谢!
    • @Gustavo:不确定这是否可行,但您可以尝试 GroupName="{Binding Description}"
    • csunwold,绑定描述没有意义,因为每个选项描述可能都是唯一的。使用您的想法,我尝试了: 1) GroupName="{Binding Question, Path=Description}" (因为 Choice 有一个指向“主”问题的属性)。这不起作用,我不知道为什么,因为如果我将 RadioButton 的内容绑定到它,它会正确显示问题描述)2)我在 Question 类上覆盖了 ToString 吐出描述并做了 GroupName="{Binding Question}"它奏效了。这真的感觉像一个黑客。
    • 可能会有这种感觉,但我越想它确实是有道理的。在使用这样的模型时,我不得不做很多覆盖 ToString 的工作。我开始认为,作为一般做法,在使用此类模型时,我应该始终覆盖 ToString,但我很想听听在这件事上有更多经验的人的意见。很高兴听到你让它工作了。
    • @csunwold:非常感谢您的帮助和意见!
    猜你喜欢
    • 2011-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-02
    • 1970-01-01
    • 2015-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多