1 回答

TA貢獻1805條經(jīng)驗 獲得超10個贊
在 WPF 中,我們使用所謂的 MVVM。我們不會像在 winforms 中那樣去查看 ListViewItem 控件,而是將所需信息的屬性放在視圖模型類上,并且使用綁定來告訴 UI 如何更新視圖模型類,反之亦然。
因此,我們將向 Question 添加 IsSelected 屬性。我們還將將該類從Questions重命名為Question,問題集合現(xiàn)在將命名Questions為Strings。
public class Question
{
public int ID { get; set; }
public string Text { get; set; }
public bool IsSelected { get; set; }
}
這是您的列表視圖。我們將 CheckBox.IsSelected 綁定到 ListViewItem.IsSelected,因此用戶只需單擊項目上的任意位置即可檢查它們。然后我們將 Question.IsSelected 綁定到 ItemContainerStyle 中的 ListViewItem.IsSelected。
<ListView
x:Name="listview"
Background="Azure"
SelectionMode="Multiple"
ItemsSource="{Binding Questions}"
>
<ListView.ItemTemplate>
<DataTemplate>
<CheckBox
IsChecked="{Binding RelativeSource={RelativeSource AncestorType=ListViewItem}, Path=IsSelected}"
Content="{Binding Text}" Margin="0,5,0,0"
/>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="IsSelected" Value="{Binding IsSelected}" />
</Style>
</ListView.ItemContainerStyle>
</ListView>
以下是我們?nèi)绾翁幚碓撌录幚沓绦蛑羞x定的問題。我猜測您的Strings收藏是 Window 或您擁有的任何視圖的成員;如果情況并非如此,請告訴我,我們將找出解決辦法。請記住,我們Questions現(xiàn)在調(diào)用該集合。
private void AddToSurvey_Click(object sender, RoutedEventArgs e)
{
string allQuestionsText = "";
foreach (var question in Questions.Where(q => q.IsSelected))
{
// I don't know what you really want to do in here, but it sounds like you do.
allQuestionsText += question.Text + "\n";
}
}
- 1 回答
- 0 關注
- 109 瀏覽
添加回答
舉報