我有checkbox
绑定到对象的属性“IsValidCustomer
”,我有一个listview
来容纳一些客户。
每当我的用户选择列表中的任何Customer
时,我希望Checkbox
Checked
属性设置为False
,这意味着我的“IsValidCustomer
”属性也会设置自动到False
。有没有办法使用WPF绑定实现这一点?
在这方面的任何帮助都会受到高度关注。
此致
-Srikanth
答案 0 :(得分:0)
首先确保您的观点Datacontext
设置为实现viewmodel
INotifyPropertyChanged
的{{1}},然后添加interface
属性保留SelectedCustomer
,
Customer
每次设置ListView
时,请检查其值并设置SelectedCustomer
属性
这里是完整的代码:
视图模型
IsValidCustomer
和视图
public class Customer
{
public String Name { get; set; }
public String Id { get; set; }
}
public partial class MainWindow : Window, INotifyPropertyChanged
{
private Customer _selectedCustomer;
public Customer SelectedCustomer
{
get
{
return _selectedCustomer;
}
set
{
if (_selectedCustomer == value)
{
return;
}
_selectedCustomer = value;
OnPropertyChanged();
IsValidCustomer = (_selectedCustomer == null);
}
}
private ObservableCollection<Customer> _listCustomers;
public ObservableCollection<Customer> ListCustomers
{
get
{
return _listCustomers;
}
set
{
if (_listCustomers == value)
{
return;
}
_listCustomers = value;
OnPropertyChanged();
}
}
private bool _isValidCustomer = false;
public bool IsValidCustomer
{
get
{
return _isValidCustomer;
}
set
{
if (_isValidCustomer == value)
{
return;
}
_isValidCustomer = value;
OnPropertyChanged();
}
}
public MainWindow()
{
InitializeComponent();
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
答案 1 :(得分:0)
我相信你的模型中有这样的东西:
private bool _IsValidCustomer;
public bool IsValidCustomer
{
get { return _IsValidCustomer; }
set
{
_IsValidCustomer= value;
PropertyChanged(this, new PropertyChangedEventArgs("IsValidCustomer"));
}
}
为该bool属性设置Binding。
<Style TargetType="ListViewItem">
<Setter Property="IsSelected" Value="{Binding IsValidCustomer, Converter={StaticResource InverseBooleanConverter}}"/>
</Style>
您的CheckBox也将受此限制:
<CheckBox IsChecked="{Binding IsValidCustomer, Mode=TwoWay}"/>
所以,我假设您从IsValidCustomer设置为true开始。在选择每一行时,您需要将其设置为false。
你需要一个反布尔转换器:
public class InverseBooleanConverter: IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
if (targetType != typeof(bool))
throw new InvalidOperationException("The target must be a boolean");
return !(bool)value;
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
#endregion
}