2011-08-03 35 views
0

我有一個包含複選框的列表視圖。如果檢查與否,我可以得到什麼?獲取WPF中的listview複選框狀態

XAML:

<ListView Name="listview1" ItemsSource="{Binding UserCollection}"> 
    <ListView.View> 
     <GridView> 
      <GridViewColumn Header="Discription" Width="170"> 
       <GridViewColumn.CellTemplate> 
        <DataTemplate> 
         <TextBlock Text="{Binding Path=Discription}" Width="Auto"/> 
        </DataTemplate> 
       </GridViewColumn.CellTemplate> 
      </GridViewColumn> 
      <GridViewColumn Header="Value" > 
       <GridViewColumn.CellTemplate> 
        <DataTemplate> 
         <StackPanel> 
          <CheckBox IsChecked="{Binding Path=Value}" Content="{Binding Path=Value}" Width="70" Name="ckBox1"/> 
         </StackPanel> 
        </DataTemplate> 
       </GridViewColumn.CellTemplate> 
      </GridViewColumn> 
     </GridView> 
    </ListView.View> 
</ListView> 

或者它可能取消選中用戶或支票在複選框收藏「價值」改變的時候?

ObservableCollection<UserData> _UserCollection = new ObservableCollection<UserData>(); 
public ObservableCollection<UserData> UserCollection 
{ 
    get { return _UserCollection; } 
} 

public class UserData 
{ 
    public string Discription { get; set; } 
    public bool Value { get; set; } 
} 

回答

1

的ObservableCollection只是引發事件時收集的內容發生變化,而不是當你的UserData類之一的屬性更改。你可能想考慮讓UserData實現INotifyPropertyChanged。這樣你可以編程設置Value屬性,UI綁定複選框會自動被選中/取消選中。

public class UserData : INotifyPropertyChanged 
    { 
     private bool m_value; 

     public bool Value 
     { 
      get { return m_value; } 
      set 
      { 
      if (m_value == value) 
       return; 
      m_value = value; 
      if (PropertyChanged != null) 
       PropertyChanged(this, new PropertyChangedEventArgs("Value")); 
      } 
     } 

     public event PropertyChangedEventHandler PropertyChanged; 
    } 
+0

同意,該方法不應該是「從ui讀取」,而是讓ui反映你的數據綁定對象。這樣你就知道該複選框是否被選中,通過查看你的對象中的相應屬性。 –

1

您應該擁有UserData implement INotifyPropertyChanged,然後在Value屬性更新時通知它。如果您不採取這兩個步驟,您的綁定將無法正常工作。一旦你完成了這兩件事,那麼UserData的實例將包含複選框的值。

public class UserData : INotifyPropertyChanged 
{ 
    /* Sample code : missing the implentation for INotifyProperty changed */ 

    private bool Value = true; 

    public bool Value 
    { 
     get{ return _value;} 
     set{ _value= value; 
      RaiseNotification("Value"); 
     }; 
    } 
} 
+0

感謝您的重播,但你可以用這個編輯我的代碼嗎?我不知道如何使用它們 –

+0

@酸我不會爲你做。如果我這樣做,你將不會學到任何東西。在我提供的MSDN鏈接上進行掠奪,或者執行Google搜索INotifyPropertyChanged –

+0

looolz謝謝你是wright –

相關問題