C# 将初始化的ViewModels添加到ObservaleCollection,显示空属性值
将ViewModels添加到ObservableCollection时,它在主窗口上显示为ItemsControl,ObservableCollection作为ItemsSource。视图的初始值显示为null。我知道这一点,因为在调试和更改文本框的值时,我看到Name字段设置为null,但当我按下按钮添加新的ViewModels时,它设置了Name字段,但没有显示名称。此应用程序已压缩以便于调试。因此,当ObservableCollection与视图通信时,它似乎没有以某种方式接收到正确的值 主窗口C# 将初始化的ViewModels添加到ObservaleCollection,显示空属性值,c#,wpf,prism,C#,Wpf,Prism,将ViewModels添加到ObservableCollection时,它在主窗口上显示为ItemsControl,ObservableCollection作为ItemsSource。视图的初始值显示为null。我知道这一点,因为在调试和更改文本框的值时,我看到Name字段设置为null,但当我按下按钮添加新的ViewModels时,它设置了Name字段,但没有显示名称。此应用程序已压缩以便于调试。因此,当ObservableCollection与视图通信时,它似乎没有以某种方式接收到正确的值
<Window x:Class="LifeCalculator.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
xmlns:myControl="clr-namespace:LifeCalculator.Views" xmlns:views="clr-namespace:LifeFinanceCalculator.Views"
Title="{Binding Title}" Height="350" Width="525">
<Grid>
<Button Margin="47,24,373,269" Content="Add ViewModels" Command="{Binding AddCommandItem}"/>
<ScrollViewer Margin="28,75,37,72">
<ItemsControl ItemsSource="{Binding ListExampleItems}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<views:exampleView/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>
<UserControl x:Class="LifeFinanceCalculator.Views.exampleView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True">
<Grid>
<TextBox Text="{Binding Name}" FontSize="22"/>
</Grid>
</UserControl>
Prism使用的
ViewModelLocator
是问题所在。ViewModelLocator
使用新的ViewModel重新初始化视图。要解决这个问题:
prism:ViewModelLocator.AutoWireViewModel=“False”
我想我知道您的意思,我假设prism ViewModelLocator可能正在重新初始化Datacontext。。。所以我当然有空值。。。听起来对吗?哦!基本上是的。这是由于多个虚拟机而导致孤立虚拟机的情况。如果有人在XAML中设置了DataContext
,并且错误地将代码隐藏,那么直接使用WPF(比如说没有棱柱,没有DI)也会发生这种情况。有人这样做过吗;)实际上,对于Prism 8,几乎在所有视图模型中都必须这样做,因为AutoWire=True是新的默认值。
<UserControl x:Class="LifeFinanceCalculator.Views.exampleView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True">
<Grid>
<TextBox Text="{Binding Name}" FontSize="22"/>
</Grid>
</UserControl>
using Prism.Mvvm;
namespace LifeFinanceCalculator.ViewModels
{
public class exampleViewModel : BindableBase
{
private string _name;
public string Name
{
get => _name;
set
{
SetProperty(ref _name, value);
}
}
public exampleViewModel()
{
}
}
}