2012-05-11 34 views
0

在DataGrid中,我顯示一個項目列表,其中包含一個由datagridviewcheckboxcolumn表示的屬性IsEnabled。 我想將複選框的數量同時限制爲5.WPF限制在datagridviewcheckboxcolumn中檢查的行數

我該怎麼做?

編輯:

我在做什麼,現在正在使用multibinding:該轉換器可以接受的項目「的IsEnabled」屬性對象和項目清單本身作爲輸入值。

<DataGrid ItemsSource="{Binding MyItems}" AutoGenerateColumns="false" 
        CanUserAddRows="False" CanUserDeleteRows="False" CanUserReorderColumns="False" CanUserSortColumns="false"> 
     <DataGrid.Columns> 
      <DataGridCheckBoxColumn Header="" Binding="{Binding Path=IsEnabled, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"> 
      <DataGridCheckBoxColumn.CellStyle> 
       <Style> 
       <Setter Property="CheckBox.IsEnabled" > 
        <Setter.Value> 
        <MultiBinding Converter="{Utilities:MyConverter}"> 
         <Binding Path="IsEnabled" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged"/> 
         <Binding Path="DataContext.MyItems" RelativeSource="{RelativeSource AncestorType=UserControl}"/> 
        </MultiBinding> 
        </Setter.Value> 
       </Setter> 
      </Style> 
      </DataGridCheckBoxColumn.CellStyle> 
      </DataGridCheckBoxColumn> 
... 

MyConverterlooks內的轉換功能是這樣的:

public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
{ 
    var val1 = (bool)values[0]; 
    int numSelected = 0; 

    if (values[1] != null && values[1] is ObservableCollection<MyTestItem>) 
    { 
    var list = (ObservableCollectionBase<MyTestItem>)values[1]; 
    foreach (MyTestItem mti in list) 
    { 
     if (mti.IsEnabled) 
     numSelected++; 
    } 
    } 
    else 
    { 
    return false; 
    } 

return val1 ? val1 : (numSelected < 5); 
} 

可正常工作(不超過5個複選框可以在同一時間,其他均爲禁用選擇),但我不斷收到類似的警告:

System.Windows.Data Warning: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.UserControl', AncestorLevel='1''. BindingExpression:Path=DataContext.MyItems; DataItem=null; target element is 'DataGridCell' (Name=''); target property is 'IsEnabled' (type 'Boolean') 

我也試着設置DataGrid的名稱,並在綁定使用「的ElementName」,但我不斷收到同樣的警告,雖然行爲是正確的。

爲什麼我會收到這些警告?

回答

0

在每個項目的ctr傳遞集合。在IsEnabled屬性上拒絕如果當前集合具有5 IsEnabled = true,則爲True。

0

將事件處理程序添加到複選框選中的事件。檢查基礎數據源的記錄以查看已檢查的數量,如果檢查的事件大於5條記錄,則取消檢查的事件。

+0

謝謝,但我想通過綁定解決這個問題,因爲我使用MVVM。所以在後面的代碼中使用checked事件處理程序不是我正在尋找的。 – tabina