【问题标题】:Bind WPF Radio Button to RadioButton within ViewModel`将 WPF 单选按钮绑定到 ViewModel 中的 RadioButton
【发布时间】:2011-05-13 22:18:12
【问题描述】:

基本上,我在用户控件中有一组单选按钮。我希望这些与它们的“对应物”相同,它们保存在 ViewModel 的列表中。

目前,我必须将每个属性的几乎所有属性都绑定到 ViewModel 集合中的适用索引。例如:

<RadioButton x:Name="btnStatus2" IsChecked="{Binding Path=radioButtonsIsChecked, Mode=TwoWay}" 
                     Content="{Binding Path=StatusButtonList[1].Content, Mode=TwoWay}"
                     Tag="{Binding Path=StatusButtonList[1].Tag, Mode=TwoWay}"
                     Visibility="{Binding Path=StatusButtonList[1].Visibility, Mode=OneWay}"
                     GroupName="statusBtns" Grid.Column="1" Grid.Row="0" >

如您所见,如果我的控件中有 10 个单选按钮,那么视图将会非常大。我对 WPF 很陌生,任何建议都将不胜感激。谢谢!

【问题讨论】:

    标签: wpf data-binding binding radio-button


    【解决方案1】:

    使用 ItemsControl 并将 ItemsSource 属性设置为视图模型中的集合。

    <ItemsControl ItemsSource="{Binding Path=RadioButtons}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <RadioButton IsChecked="{Binding Path=IsRadioButtonChecked}" />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
    

    WPF 中还有一些特殊的 ItemsControl 派生类型,它们提供附加功能(滚动、选定项等)。 ListView、ListBox、ComboBox、DataGrid、TreeView等都是可以在这里使用的ItemsControl

    【讨论】:

    • 好的,谢谢哥们。看起来这是最好的解决方案,但是将这些项目放入网格等中存在挑战,因为其中有 10 个。这是我挂断的部分。我在想我可以以编程方式指定网格值吗?原谅我周五下午的敏感……
    • 一个 ItemsControl 有一个 ItemsPanelTemplate 属性,它指定项目的布局。默认情况下,它使用 StackPanel,因此您不再需要在 RadioButtons 上指定 Grid.Column 和 Grid.Row。单选按钮只会堆叠在一起
    猜你喜欢
    • 2011-05-20
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    • 1970-01-01
    • 2014-02-03
    • 2010-11-22
    • 2011-08-17
    • 2017-12-23
    相关资源
    最近更新 更多