【发布时间】:2018-07-25 07:00:36
【问题描述】:
为了保持我的 MainWindow.xaml.cs 干净,我尝试将所有内容外包给 ViewModel 类,然后将我的视图绑定到我的 ViewModel 属性的属性
然而,使用这个额外的层似乎不起作用。我的列表和文本框保持空白。有什么方法可以让这个方法起作用吗?
MainWindow 类:
public partial class MainWindow : Window, INotifyPropertyChanged
{
public ViewModel ViewModel { get; set; }
public MainWindow()
{
InitializeComponent();
ViewModel = new ViewModel();
}
}
ViewModel 类:
public class ViewModel : INotifyPropertyChanged
{
private string m_oneLineOnly;
private ObservableCollection<string> m_sampleLines;
public ObservableCollection<string> SampleLines
{
get => m_sampleLines;
set
{
m_sampleLines = value;
RaisePropertyChanged(nameof(SampleLines));
}
}
public string OneLineOnly
{
get => m_oneLineOnly;
set
{
m_oneLineOnly = value;
RaisePropertyChanged(nameof(OneLineOnly));
}
}
public ViewModel()
{
SampleLines = new ObservableCollection<string>(new List<string>()
{
"Gedanken",
"Zeit",
"Sand"
});
OneLineOnly = "Hello World";
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private void RaisePropertyChanged(string propertyName)
{
var handlers = PropertyChanged;
handlers(this, new PropertyChangedEventArgs(propertyName));
}
}
主窗口 XAML
<Window x:Class="DataContext_Test_Project.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:DataContext_Test_Project"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800"
x:Name="Window">
<Grid>
<ListBox
HorizontalAlignment="Left"
Height="100"
Margin="334,132,0,0"
VerticalAlignment="Top"
Width="100"
ItemsSource="{Binding ElementName=Window, Path=ViewModel.SampleLines}"/>
<TextBox
HorizontalAlignment="Left"
Height="23"
Margin="184,166,0,0"
TextWrapping="Wrap"
VerticalAlignment="Top"
Width="120"
DataContext="{Binding ElementName=Window, Path=ViewModel}"
Text="{Binding Path=OneLineOnly}"/>
</Grid>
【问题讨论】:
-
您的输出窗口是否显示绑定错误?尝试使用此方法添加有关绑定的更多信息并查看它们解析到的位置:spin.atomicobject.com/2013/12/11/wpf-data-binding-debug
-
只需在
InitializeComponent();之前调用ViewModel = new ViewModel();,一切正常。
标签: c# wpf xaml mvvm data-binding