我有一个 Switch 绑定(bind)到列表中元素的属性。我想将按钮的 IsVisible 绑定(bind)到同一属性,但当属性由 Switch 更改时,按钮的可见性不会更改。我错过了什么?
XAML:
<StackLayout>
<ListView HorizontalOptions="FillAndExpand" ItemsSource="{Binding EquipmentList}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding Name}" />
<Switch IsToggled="{Binding State}" />
<Button
Command="{Binding BindingContext.DoCommand, Source={x:Reference TestPage}}"
CommandParameter="{Binding .}"
IsVisible="{Binding State}"
Text="Click" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
View 模型:
private Command<Equipment> _doCommand;
public Command<Equipment> DoCommand => _doCommand ??
(_doCommand = new Command<Equipment>((Equipment obj) => HandleEquipment(obj)));
// Outputs correct Name and State of the list item
private void HandleEquipment(Equipment obj)
{
System.Diagnostics.Debug.WriteLine(obj.Name + ", " + obj.State);
}
型号:
class Equipment
{
public int Id { get; set; }
public string Name { get; set; }
public bool State { get; set; }
public Equipment(int Id, string Name, bool State)
{
this.Id = Id;
this.Name = Name;
this.State = State;
}
}
最佳答案
正如 Gerald 在他的第一条评论中所写:您必须在 Equipment
模型上(而不仅仅是在 ViewModel 中)实现 INotifyPropertyChanged
接口(interface)。
如果没有这种实现, View 中的元素就没有机会知道状态发生了变化(在您的例子中是按钮)。
实现:
public class Equipment: INotifyPropertyChanged
{
public bool State
{
get => _state;
set =>
{
_state = value;
OnPropertyChanged();
}
}
private bool _state;
// OTHER PROPERTIES
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
方法OnPropertyChanged()
的调用很重要。按钮的 IsVisible
属性会识别更改并更新其值。
关于xaml - 将 IsVisible 绑定(bind)到由 Switch 切换的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53335995/