c# - ListView 的数据模板中的单选按钮组

标签 c# wpf listview mvvm .net-4.0

我的问题是以下答案的延伸。它指出单选按钮的 GroupName 范围很广,通常最好让容器自动分配 GroupName。

https://stackoverflow.com/a/6062697/907920

如果我使用静态 GroupName,则所有 RadioButton 都共享该组。 (如链接中的答案所示。)

但是,如果我不使用 GroupName,那么每个单独的 RadioButton 都会被视为单独在一个组中。为了自动分配 GroupName,我只能假设它使用 DataTemplate 或 CellTemplate 作为“父级”。

我在 StackPanel 中有一个问题列表。每个问题都显示在用户控件中。每个问题都包含一个答案 ListView 。每个 Answer 都有一个 bool 值属性,指示已选择答案,该属性绑定(bind)到 DataTemplate 内的 RadioButton。

我的精简 XAML 如下

    <ListView ItemsSource="{Binding AnswerList}" >
      <ListView.View>
        <GridView>
          <!-- Other columns here -->
          <GridViewColumn>
            <GridViewColumn.CellTemplate>
              <DataTemplate>
                <RadioButton IsChecked="{Binding Path=AnswerChecked}" />
              </DataTemplate>
            </GridViewColumn.CellTemplate>
          </GridViewColumn>
        </GridView>
      </ListView.View>
    </ListView>

我认为除了使用 ListView 我别无选择,因为我需要能够关闭和打开其他列,并且需要显示两个或更多答案。

有没有办法让我告诉单选按钮它是 UserControl 的一部分,而不是出于其 GroupName 目的的 DataTemplate?

我考虑过为每个 UserControl 分配一个 GUID,并将 RadioButtons 的 GroupName 绑定(bind)到 GUID 的字符串,但这似乎过于繁琐且笨拙。

编辑:为了视觉引用,用户界面大约像这样流动,括号中是我的注释:

(绑定(bind)到问题集合的问题堆栈面板)

  1. 问题控件(包含绑定(bind)到答案集合的 ListView,“|”分隔列)
    • [ ] |答案 1(带有文本“答案 1”的未经检查的答案对象)
    • [ ] |答案 2
    • [*] |答案 3(带有文本“答案 3”的选中答案对象)
  2. 第 16 任总统是谁
    • [ ] |卡尔·马克思
    • [*] |亚伯拉罕·林肯
    • [ ] |理查德·尼克松
  3. 一摩尔氢气的重量是多少
    • [ ] | 10克
    • [ ] | .1克
    • [ ] | 1克

最佳答案

你应该能够摆脱这样的事情

 <RadioButton GroupName="{Binding}" IsChecked="{Binding Path=AnswerChecked}" />

这应该将它们组合在一起。

如果 ListView 是 QuestionControl 的一部分,为什么不绑定(bind) QuestionText,因为问题应该是唯一的

<RadioButton GroupName="{Binding Path=TheQuestionText}" IsChecked="{Binding Path=AnswerChecked}" />

您可能必须使用 FindAncestorDataTemplate 访问您的 Questioncontrol

 <RadioButton GroupName="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type QuestionControl}}, Path=QuestionText"}  />

关于c# - ListView 的数据模板中的单选按钮组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14043922/

相关文章:

C# 不通过返回类型推断重载方法

android - 在 Android 中单击适配器中的按钮时,无法刷新从 JSON 获取数据的 ListView

wpf - 如何在重置数据时重置 WPF 工具包图表调色板

c# - 使用 CSWinRT 调用 .net5 windows api

wpf - 如何在 WPF 中将 TargetType 设置为此?

java - 在sqlite中使用intent后如何从listview中获取项目名称?

Android 如何正确通知 ListView 的数据集已更改

c# - 如何以编程方式选择 ListView 项目?

c# - Windows 商店应用程序中的密码散列

c# - PDF 签名 - 嵌入单独签名的哈希