需要帮助修复我的委托事件传递GUID给我的MainViewModel来创建订单



在我的CustomerListViewModel中我定义了一个'委托'事件,它需要调用我的mainViewModel中的一个方法,并将我的客户的GUID传递给这个vm中定义的方法。只有委托不能正常工作,事件从未传递给我的mainViewModel:(

public partial class CustomerListViewModel : ObservableObject
{
public CustomerListViewModel()
{
customerCollection = new ObservableCollection<Customer>();
Customer jacob = new Customer("Jacob", "Woord", "NederLand");
Customer Maria = new Customer("Maria", "Woord", "Nederland");

customerCollection.Add(jacob);
customerCollection.Add(Maria);


}
public event Action<Guid> PlaceOrderRequested = delegate { };
[RelayCommand]
void PlaceOrder(Customer obj)
{
PlaceOrderRequested(obj.CustomerId);
}

[ObservableProperty]
ObservableCollection<Customer> customerCollection;
// Can Execute Example (if there no item selected in the list the button get disbled
public bool canDelete => selectedCustomer != null;


[RelayCommand(CanExecute =nameof(canDelete))]
void Delete()
{
customerCollection.Remove(selectedCustomer);
}
//Notifys the change for the selected Customer
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(DeleteCommand))]
Customer selectedCustomer;
[RelayCommand]
void DeleteAll()
{
customerCollection.Clear();
}
namespace viewModelBinding
{
public partial class MainWIndowViewModel : ObservableObject
{
//intialize every vieModel
private CustomerListViewModel customerListViewModel = new CustomerListViewModel();
private MaterialListViewModel materialListViewModel = new MaterialListViewModel();
private OrderListViewModel    orderListViewModel = new OrderListViewModel();
private OrderPrepViewModel    orderPrepViewModel = new OrderPrepViewModel();
private Timer timer = new Timer(5000);
public MainWIndowViewModel()
{
customerListViewModel.PlaceOrderRequested += CustomerListViewModel_PlaceOrderRequested;
currentViewModel = new OrderListViewModel();
timer.Elapsed += (s, e) => NotificationMessage = "Na 5 seconden word de huidige tijd neergzet: " + DateTime.Now.ToLocalTime() + " Kukulukuu";
timer.Start();
}
private void CustomerListViewModel_PlaceOrderRequested(Guid obj)
{
orderListViewModel.CustomerId = obj;
currentViewModel = orderListViewModel;
}
[ObservableProperty]
object currentViewModel;
[ObservableProperty]
string notificationMessage;



//switch statement with a parameter that gets a command parameter from the button as a string
[RelayCommand]
void OnNav(string destination)
{
switch (destination)
{
case "orders":
CurrentViewModel = orderListViewModel;
break;
case "customers":
CurrentViewModel = customerListViewModel;
break;
default:
CurrentViewModel = materialListViewModel;
break;
}
}


}
}

在我定义绑定

的视图下面
<UserControl x:Class="viewModelBinding.Customers.CustomerListView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
xmlns:local="clr-namespace:viewModelBinding.Customers"
xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
mc:Ignorable="d" 
d:DesignHeight="450" d:DesignWidth="800">
<UserControl.InputBindings>
<KeyBinding Key="D" Modifiers="Control" Command="{Binding DeleteCommand}"/>
</UserControl.InputBindings>
<UserControl.Resources>

<DataTemplate x:Key="CustomerListTemplate">

<Border BorderThickness="2"
BorderBrush="red">
<StackPanel>
<TextBlock Text="{Binding FirstName}"/>
<TextBlock Text="{Binding LastName}"/>
<TextBlock Text="{Binding CityCustomer}"/>
</StackPanel>
</Border>

</DataTemplate>
</UserControl.Resources>
<UserControl.DataContext>
<local:CustomerListViewModel/>
</UserControl.DataContext>
<!--<b:Interaction.Triggers>

<b:EventTrigger EventName="">
<b:CallMethodAction TargetObject="{Binding}" MethodName="{Binding DeleteAllCommand}"/>
</b:EventTrigger>
</b:Interaction.Triggers>-->

<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="2*"/>
<RowDefinition Height="1*"/>
</Grid.RowDefinitions>
<Button Grid.Row="0"
Content="Delete"
HorizontalAlignment="Left"
Width="75"
Command="{Binding DeleteCommand}"/>
<Button Grid.Row="0"
Content="empty"
HorizontalAlignment="Right"
Width="75"
/>

<DataGrid ItemsSource="{Binding CustomerCollection}"
Grid.Row="1"
x:Name="CustomerList"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn x:Name="nameColumn"
Binding="{Binding FirstName}"
Width="*"/>
<DataGridTemplateColumn Width="auto">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<!--with this command we grap the dataContext of the right customer to look at the anchestor (DataGrid)-->
<Button Content="Place Order"
Command="{Binding DataContext.PlaceOrderCommand,RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
CommandParameter="{Binding}"
Margin="5"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Binding="{Binding CustomerId}" Width="auto">

</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>

<ListBox SelectedItem="{Binding SelectedCustomer}" 
ItemsSource="{Binding CustomerCollection}" 
Grid.Row="2" ItemTemplate="{StaticResource CustomerListTemplate}"/>


</Grid>
</UserControl>

你的问题是因为你有两个CustomerListViewModel的实例

这是一个例子。(去掉它)

<UserControl.DataContext>
<local:CustomerListViewModel/>
</UserControl.DataContext>

这是另一个。

private CustomerListViewModel customerListViewModel = new CustomerListViewModel();

但是委托的方法是一个坏主意。

我推荐使用messenger而不是delegate。

与其传递硬引用,不如保持两个视图模型解耦。

https://learn.microsoft.com/en-us/windows/communitytoolkit/mvvm/messenger

//创建消息LoggedInUserChangedMessage: ValueChangedMessage{public LoggedInUserChangedMessage(User User): base(User){
}}

// Register a message in some module
WeakReferenceMessenger.Default.Register<LoggedInUserChangedMessage>(this, 
(r, m) =>
{
// Handle the message here, with r being the recipient and m being the
// input message. Using the recipient passed as input makes it so that
// the lambda expression doesn't capture "this", improving performance.
});
// Send a message from some other module
WeakReferenceMessenger.Default.Send(new LoggedInUserChangedMessage(user));

显然,这里你想在你发送的对象中传递一个guid。您可以在其他地方传递一个类型,甚至整个视图模型用于导航。

这似乎很奇怪,你正在传递一个guid回mainwindowviewmodel

我本以为会有订单和新订单的视图。新订单会让你挑选一个客户所以会有一些子视图让你查找客户。选择客户的命令将位于新订单视图模型中,并从客户视图绑定,因此该命令传递了客户id。

也许这只是纯粹的实验代码。

最新更新