WPF binding to Listbox selectedItem

前端 未结 5 1440
再見小時候
再見小時候 2020-12-13 18:19

Can anyone help with the following - been playing about with this but can\'t for the life of me get it to work.

I\'ve got a view model which contains the following p

5条回答
  •  悲哀的现实
    2020-12-13 18:50

    Inside the DataTemplate you're working in the context of a Rule, that's why you cannot bind to SelectedRule.Name -- there is no such property on a Rule. To bind to the original data context (which is your ViewModel) you can write:

    
    

    UPDATE: regarding the SelectedItem property binding, it looks perfectly valid, I tried the same on my machine and it works fine. Here is my full test app:

    XAML:

    
        
            
        
        
            
                
                    
                        
                        
                    
                
            
        
    
    

    Code behind:

    namespace TestWpfApplication
    {
        /// 
        /// Interaction logic for ListBoxSelectedItem.xaml
        /// 
        public partial class ListBoxSelectedItem : Window
        {
            public ListBoxSelectedItem()
            {
                InitializeComponent();
            }
        }
    
    
        public class Rule
        {
            public string Name { get; set; }
        }
    
        public class ListBoxSelectedItemViewModel
        {
            public ListBoxSelectedItemViewModel()
            {
                Rules = new ObservableCollection()
                {
                    new Rule() { Name = "Rule 1"},
                    new Rule() { Name = "Rule 2"},
                    new Rule() { Name = "Rule 3"},
                };
            }
    
            public ObservableCollection Rules { get; private set; }
    
            private Rule selectedRule;
            public Rule SelectedRule
            {
                get { return selectedRule; }
                set
                {
                    selectedRule = value;
                }
            }
        }
    }
    

提交回复
热议问题