c# - 如何根据 Xamarin 和 XAML 中的绑定属性更改按钮的属性
问题描述
我正在尝试使用 XAML 和 Xamarin 创建一个列表视图,其中包含带有用户信息的标签。有人应该能够从列表中选择多个用户。如果他们愿意,他们可以使用顶部的“全选”按钮。
未选中的人应该有一个带有“显示兴趣”文本的灰色按钮。选定的人应该有一个带有“删除兴趣”文本的绿色按钮。
我通过创建一个包含我需要的信息以及以下信息的类来做到这一点:
public bool IsSelected { get; set; }
public Color ButtonColor { get { return IsSelected ? Color.LightGreen : Color.LightGray; } }
public string Status { get { return IsSelected ? "Remove\nInterest" : "Show\nInterest"; } }
在 xaml 中,我将按钮的属性绑定到颜色和状态:
<ListView x:Name="ItemsListView"
ItemsSource="{Binding Results}"
VerticalOptions="FillAndExpand"
HasUnevenRows="True"
IsPullToRefreshEnabled="False">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid>
<Button
Text="{Binding Status}"
BackgroundColor="{Binding ButtonColor}"
Clicked="ChangeInterest"
Grid.Row="0"
Grid.RowSpan="6"
Grid.Column="10"
Grid.ColumnSpan="5"
/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
ChangedInterest 只是找到适当的项目并切换“IsSelected”。既然属性绑定了变量,变量绑定了IsSelected,那么按钮不应该自动改变吗?
如果在 ChangedInterest 函数中,我
(sender as Button).Text = Results[i].Status;
为颜色写了相应的行,它就会改变。
“全选”按钮只是滚动列表中的所有项目并将 IsSelected 设置为每个项目为真。期望的结果是所有按钮随后根据第一个块的规则更改颜色和文本。
有没有办法让属性随着绑定的变化而自动变化?
解决方案
虽然您使用过数据绑定,但您可以使用Command代替按钮的ClickEvent。
在xml中
<Button
Text="{Binding Status}"
BackgroundColor="{Binding ButtonColor}"
Command="{Binding Selected}"
Grid.Row="0"
Grid.RowSpan="6"
Grid.Column="10"
Grid.ColumnSpan="5"/>
在你的模型中
public class Model : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
bool isSelected;
public bool IsSelected {
get { return isSelected; }
set {
isSelected = value;
NotifyPropertyChanged();
if(value)
{
ButtonColor = Color.LightGreen;
Status = "Remove\nInterest";
}
else
{
ButtonColor = Color.LightGray;
Status = "Show\nInterest";
}
}
}
Color buttonColor;
public Color ButtonColor {
get { return buttonColor; }
set {
buttonColor = value;
NotifyPropertyChanged();
}
}
string status;
public string Status {
get { return status; }
set {
status = value;
NotifyPropertyChanged();
}
}
public ICommand Selected { get; private set; }
public Model()
{
Selected = new Command(() => { IsSelected = !IsSelected; });
}
protected virtual void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
推荐阅读
- c# - 属性更改时不会触发 INotifyPropertyChanged
- javascript - 找到最短的数学运算序列
- java - 使用 Mockito 模拟使用 Pageable 和 Slice 接口的 DB 调用时出现 NullPointerException
- javascript - jQuery - 使用全局函数
- keras - keras:如何在损失评估中添加权重
- python - 在行中剪切数据框
- java - 升级 spring-boot-starter-parent 后 WebApplicationInitializer 不起作用
- javascript - 角度形式的补丁值
- python - 在作为子集的集合列表中查找集合并选择它们
- python - 识别列表中的不同元素并将其映射到python中另一个列表中的相应索引