在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」,但我不斷收到同樣的警告,雖然行爲是正確的。
爲什麼我會收到這些警告?
謝謝,但我想通過綁定解決這個問題,因爲我使用MVVM。所以在後面的代碼中使用checked事件處理程序不是我正在尋找的。 – tabina