我正在使用 .NET Maui 使用 MVVM 开发 Windows 桌面应用。
我有 2 Pickers
与 ImageSource
和 SelectedIndex
绑定(bind)到 View 模型中的属性。当从第一个 Picker
中选择一个项目时other 中的项目需要更改。我想绑定(bind) SelectedIndexChanged
将事件发送到 View 模型中的方法以完成此操作。
选取器中事件的 XAML Picker
看起来像这样:
<Picker SelectedIndexChanged="{Binding OnSelectedIndexChanged}" />
viewmodel 中的方法如下所示:
public void OnSelectedIndexChanged(object sender, EventArgs e)
{
// do stuff
}
但是在运行程序时出现如下错误:
XFC0009 No property, BindableProperty, or event found for "SelectedIndexChanged", or mismatching type between value and property. MauiApp1
我的临时解决方案是在事件触发时从后台代码调用 viewmodel 方法。后面的代码如下所示:
private void Picker_SelectedIndexChanged(object sender, EventArgs e)
{
(BindingContext as MainViewModel).OnSelectedIndexChanged(sender, e);
}
我想让代码尽可能地笨拙。 有没有办法处理 SelectedIndexChanged
通过直接绑定(bind)到 View 模型中的方法来处理事件?
更新 尝试执行partial void On<PropertyName>Changed()
我的 View 模型:
public partial class MainViewModel : ObservableObject
{
[ObservableProperty]
private ObservableCollection<ProductGroupRoot> itemSourceProductGroups = new();
[ObservableProperty]
private int selectedProductGroup = -1;
[ObservableProperty]
private ObservableCollection<ProductRoot> itemSourceProducts = new();
[ObservableProperty]
private int selectedProduct = -1;
// other properties
partial void OnSelectedProductGroupChanged(int value)
{
// TODO: change values in ItemSourceProducts
}
}
自动生成的代码应该已经为部分方法创建了一个定义,但是我得到了错误:
CS0759 No defining declaration found for implementing declaration of partial method 'MainViewModel.OnSelectedProductGroupChanged(int)'
我正在使用 CommunityToolkit.Mvvm v7.1.2(最新稳定版)。
更新 2 发布工作代码。
我的 csproj 文件:
<Project>
<ItemGroup>
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.0.0-preview4" />
</ItemGroup>
</Project>
我的选择器:
<Picker ItemsSource="{Binding ProductGroups, Mode=TwoWay}"
SelectedIndex="{Binding ProductGroupsIndex, Mode=TwoWay}" />
我的 View 模型:
[ObservableProperty]
private ObservableCollection<ProductGroupRoot> productGroups = new();
[ObservableProperty]
private int productGroupsIndex = -1;
partial void OnProductGroupsIndexChanged(int value) {}
最佳答案
当属性绑定(bind)到 SelectedIndex
时,您可以简单地更改第二个选择器项目变化。
由于您使用的是 MVVM CommunityToolkit,要在属性更改后执行一些代码,您必须实现一个在自动生成的类中定义的分部方法。
此方法称为 On<YourPropertyName>Changed()
.
请注意,此功能仅在 8.0.0 版本后可用。
关于c# - .NET Maui MVVM Picker 绑定(bind) SelectedIndexChanged 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72562345/