在我的 .NET 8 MAUI 项目中,我创建了一个类似
ContentView
的组件。我向该组件传递了一个名为 Values
的属性。
定义如下:
public partial class EntryChoices : ContentView
{
public static readonly BindableProperty ValuesProperty =
BindableProperty.Create(nameof(Values),
typeof(List<string>), typeof(EntryChoices),
null, BindingMode.TwoWay);
public List<string>? Values
{
get => (List<string>)GetValue(ValuesProperty);
set => SetValue(ValuesProperty, value);
}
}
在 XAML 中,我使用此值来绑定
FlexLayout
<ContentView
x:Name="cv">
<VerticalStackLayout BindingContext="{x:Reference cv}"
VerticalOptions="FillAndExpand">
<FlexLayout
x:Name="FlexSkillContainer"
BindableLayout.ItemsSource="{Binding Values}">
<BindableLayout.ItemTemplate>
<DataTemplate>
<!-- More XAML -->
</DataTemplate>
</BindableLayout.ItemTemplate>
</FlexLayout>
</VerticalStackLayout>
</ContentView>
如果我向
Values
添加一些值,这不会改变 UI。我尝试添加
OnPropertyChanged(nameof(Values));
但这没有帮助,也没有将
INotifyPropertyChanged
添加到 ContentView
。功能如下
public void AddItem(string item)
{
if (Values == null)
Values = new List<string>();
Values.Add(item);
OnPropertyChanged(nameof(Values));
OnPropertyChanged(nameof(ValueString));
}
我找不到在
Values
更改时更新 UI 的方法。
更新:现在
Values
是ObservableCollection
:
public static readonly BindableProperty ValuesProperty =
BindableProperty.Create(nameof(Values),
typeof(IEnumerable<string>), typeof(EntryChoices),
defaultBindingMode: BindingMode.TwoWay,
propertyChanged: OnValueChanged);
public ObservableCollection<string>? Values
{
get => (ObservableCollection<string>)GetValue(ValuesProperty);
set => SetValue(ValuesProperty, value);
}
在 XAML 中,我将此视图称为
<components:EntryChoices
x:Name="entryOriginal"
Values="{Binding OriginalList}" />
OriginalList
是视图模型定义为
[ObservableProperty]
private ObservableCollection<string> _originalList;
如果我为该属性分配一个
List
以及一些值,例如
OriginalList = new ObservableCollection<string>(vl);
组件不会触发属性集
Values
。
虽然 BindableProperty 的
Setter
不触发,但 UI 应该更改。您不需要在 set 访问器中添加任何额外的逻辑。相反,您可以将逻辑放在 property-changed callback method
,
private static void OnValueChanged(BindableObject bindable, object oldValue, object newValue)
{
var ec = bindable as EntryChoices;
ec.OnPropertyChanged(nameof(ValueString));
}
更多信息,您可以参考检测属性变化。