2010-12-12 18 views
9

मेरे पास मेरे प्रोग्राम में ItemsControl है जिसमें रेडियो बटन की एक सूची है।समूह में चयनित रेडियो बटन प्राप्त करें (डब्ल्यूपीएफ)

<ItemsControl ItemsSource="{Binding Insertions}"> 
     <ItemsControl.ItemTemplate> 
      <DataTemplate> 
       <Grid> 
        <RadioButton GroupName="Insertions"/> 
       </Grid> 
      </DataTemplate> 
     </ItemsControl.ItemTemplate> 
    </ItemsControl> 

मैं समूहInsertions एक MVVM ढंग से में चयनित रेडियो बटन कैसे पता करूं?

इंटरनेट पर पाए गए अधिकांश उदाहरणों में व्यक्तिगत बूलियन गुणों को स्थापित करना शामिल है जो आप कनवर्टर की सहायता से IsChecked संपत्ति को बांधते हैं।

क्या ListBoxSelectedItem के बराबर है जो मैं बांध सकता हूं?

उत्तर

9

एक समाधान जो दिमाग में आता है वह है IsChecked बूलियन संपत्ति को अपनी प्रविष्टि इकाइयों में जोड़ना और उसे रेडियो बटन की 'Ischecked' संपत्ति से जोड़ना है। इस तरह आप व्यू मॉडल में 'चेक किए गए' रेडियो बटन को देख सकते हैं।

यहां एक त्वरित और गंदा उदाहरण है।

एनबी: मैं तथ्य यह है कि IsChecked भी null हो सकता है पर ध्यान नहीं दिया, तो आप को संभाल सकता है कि bool? का उपयोग कर यदि आवश्यक हो।

सरल ViewModel

using System; 
using System.Collections.Generic; 
using System.Collections.ObjectModel; 

namespace WpfRadioButtonListControlTest 
{ 
    class MainViewModel 
    { 
    public ObservableCollection<Insertion> Insertions { get; set; } 

    public MainViewModel() 
    { 
     Insertions = new ObservableCollection<Insertion>(); 
     Insertions.Add(new Insertion() { Text = "Item 1" }); 
     Insertions.Add(new Insertion() { Text = "Item 2", IsChecked=true }); 
     Insertions.Add(new Insertion() { Text = "Item 3" }); 
     Insertions.Add(new Insertion() { Text = "Item 4" }); 
    } 
    } 

    class Insertion 
    { 
    public string Text { get; set; } 
    public bool IsChecked { get; set; } 
    } 
} 

XAML - कोड के पीछे नहीं दिखाया गया है के बाद से यह उत्पन्न कोड से के अलावा अन्य कोई कोड है।

<Window x:Class="WpfRadioButtonListControlTest.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:WpfRadioButtonListControlTest" 
     Title="MainWindow" Height="350" Width="525"> 
    <Window.Resources> 
    <local:MainViewModel x:Key="ViewModel" /> 
    </Window.Resources> 
    <Grid DataContext="{StaticResource ViewModel}"> 
    <ItemsControl ItemsSource="{Binding Insertions}"> 
     <ItemsControl.ItemTemplate> 
     <DataTemplate> 
      <Grid> 
      <RadioButton GroupName="Insertions" 
         Content="{Binding Text}" 
         IsChecked="{Binding IsChecked, Mode=TwoWay}"/> 
      </Grid> 
     </DataTemplate> 
     </ItemsControl.ItemTemplate> 
    </ItemsControl> 
    </Grid> 
</Window> 
संबंधित मुद्दे