2010-12-21 9 views
7

मेरे पास एक सूची बॉक्स है जो MyObjects का संग्रह प्रदर्शित करता है। संग्रह ViewModel में है। मैं ListItem पर बटन पर एक क्लिक को संभालना चाहता हूं लेकिन बाध्यकारी के साथ कुछ परेशानी है। डेटा टेम्पलेट में बाध्यकारी ठीक काम करता है अगर संपत्ति MyObject संपत्ति से जुड़ी है। लेकिन मैं इसे ViewModel से संपत्ति में कैसे बांध सकता हूं?व्यूमोडेल के गुणों में ListBox के आइटम्स में बाइंडिंग का उपयोग कैसे करें

दूसरा प्रश्न मैं कोड में आइटम से जानकारी का उपयोग कैसे कर सकता हूं जो क्लिक ईवेंट को संभालता है। उदाहरण के लिए, मैं आइटम के टेक्स्टबॉक्स से टेक्स्ट प्रिंट करना चाहता हूं।

कोड कि तरह है:

<Window.Resources> 
    <DataTemplate x:Key="ItemTemplate"> 
     <Button Content="{Binding .}" 
       Command="{Binding ClickCommand}" /> <!--It doesn't work--> 
    </DataTemplate> 

</Window.Resources> 
<ListBox x:Name="ListBox" 
     ItemsSource="{Binding Path=Objects}" 
     IsSynchronizedWithCurrentItem="True" 
     ItemTemplate="{StaticResource ItemTemplate}"/> 

सी #:

public partial class MainWindow : Window 
{ 
    VM m_vm; 

    public MainWindow() 
    { 
     m_vm = new VM(); 
     this.DataContext = m_vm; 
     InitializeComponent(); 
    } 
} 

public class VM 
{ 
    ObservableCollection<string> _objects; 

    public ObservableCollection<string> Objects 
    { 
     get { return _objects; } 
     set { _objects = value; } 
    } 

    public VM() 
    { 
     _objects = new ObservableCollection<string>(); 
     Objects.Add("A"); 
     Objects.Add("B"); 
     Objects.Add("C"); 
    } 

    //I used relayCommand from the John Smith articles 
    RelayCommand _clickCommand; 
    public ICommand ClickCommand 
    { 
     get 
     { 
      if (_clickCommand == null) 
      { 
       _clickCommand = new RelayCommand(() => this.AvatarClick()); 
      } 
      return _clickCommand; 
     } 
    } 

    public void AvatarClick() 
    { 
     //how to get here the text from the particular item where the button was clicked? 
    } 
} 

उत्तर

11

आपका ListBoxItem के DataContext के रूप में और वहाँ से आप किसी भी AvatarClick RelayCommand नहीं है ObservableCollection वस्तुओं से स्ट्रिंग आइटम होंगे । आप इसके बजाय मूल सूचीबॉक्स से DataContext का उपयोग करने के लिए बाध्यकारी में सापेक्ष स्रोत का उपयोग कर सकते हैं।

अपने दूसरे प्रश्न के लिए, तो आप इस

Xaml

<DataTemplate x:Key="ItemTemplate"> 
    <Button Content="{Binding .}" 
      Command="{Binding DataContext.ClickCommand, 
           RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}" 
      CommandParameter="{Binding .}"/> 
</DataTemplate> 

ViewModel

public ICommand ClickCommand 
{ 
    get 
    { 
     if (_clickCommand == null) 
     { 
      _clickCommand = new RelayCommand(param => this.AvatarClick(param)); 
     } 
     return _clickCommand; 
    } 
} 

public void AvatarClick(object param) 
{ 
    //... 
} 
तरह CommandParameter का उपयोग कर सकता
संबंधित मुद्दे