【问题标题】:How can I do TwoWay binding to the selected index of a radio button?如何对单选按钮的选定索引进行双向绑定?
【发布时间】:2011-12-08 14:22:54
【问题描述】:

我有一个对象列表(由一个 int 类型的 ID 和一个字符串组成),每个对象代表一个选项并对应一个单选框。我有一个int selectedChoice,它代表所选单选框的 ID,代表一个选项。我希望int SelectedChoice 和实际选中的单选框相互绑定(双向绑定)。

使用 ItemTemplate 和 ItemsSource 将单选框添加到列表框中。

如何做到这一点?试了这么多方法,没有一个行得通。


我试过了

  • 转换器(但不支持ConverterParameter中的绑定)
  • 添加一个可以识别选中的单选框的整个类,并且还带有int SelectedChoice。但是这种方法在转换回来时会失败,因为我没有得到任何必要的信息。
  • 使用DependencyObject,当我尝试将其绑定到它时会失败,因为Binding.Converter 中没有DataContext,而且我在 Internet 上找到的解决方法仅适用于 WPF。
  • IMultiConverter 在 SilverLight 中根本不存在

【问题讨论】:

    标签: silverlight xaml windows-phone-7 data-binding


    【解决方案1】:
    public class Choice : BaseModel
    {
        private int id;
        public int Id
        {
            get { return id; }
            set 
            {
                id = value;
                NotifyPropertyChanged("Id");
            }
        }
    
        private bool isSelected;
        public bool IsSelected
        {
            get { return isSelected; }
            set
            {
                isSelected = value;
    
                if (isSelected)
                {
                    App.viewModel.SelectItem(Id);
                }
                NotifyPropertyChanged("IsSelected");
            }
        }
    
        private string text;
        public string Text
        {
            get { return text; }
            set
            {
                text = value;
                NotifyPropertyChanged("Text");
            }
        }
    }
    

    .

    public class ViewModel : BaseViewModel
    {
        public ObservableCollection<Choice> Choices {get; set;}
    
        public int SelectedChoice { get; private set; }
    
        public ViewModel()
        {
            Choices = new ObservableCollection<Choice>();
            Choices.Add(new Choice() { Id = 0, Text = "1" });
            Choices.Add(new Choice() { Id = 1, Text = "2" });
            Choices.Add(new Choice() { Id = 2, Text = "3" });
        }
    
        public void SelectItem(int Id)
        {
            SelectedChoice = Id;
            MessageBox.Show(SelectedChoice.ToString());
            foreach (var choice in Choices)
            {
                if (choice.Id != Id)
                {
                    choice.IsSelected = false;
                }
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      您可以设置列表框的样式,使其具有单选按钮和列表框项。列表框 itemssource 将绑定到您的项目列表。然后像往常一样使用 selecteditem 或 selectedvalue 属性。

      How to implement a XAML Radio Button control with an ObservableCollection source?

      Binding selectedItem ListBox of Radio buttons in combobox popup

      【讨论】:

      • 这正是我的想法:我做错了整件事。我只是没有走上解决方案的正确道路。谢谢!
      猜你喜欢
      • 1970-01-01
      • 2016-04-10
      • 1970-01-01
      • 1970-01-01
      • 2023-01-11
      • 1970-01-01
      • 1970-01-01
      • 2017-02-28
      • 1970-01-01
      相关资源
      最近更新 更多