【发布时间】:2018-04-15 10:39:54
【问题描述】:
在应用程序中,我想绑定来自 2 个不同视图模型的数据。我必须将 datacontext 设置为两个不同的视图模型。
当我使用两个不同的视图模型时,只有最后一组数据上下文优先。
因此,我有一个带有其他视图模型类的 CombinedDataContext 类。
我可以更新到视图模型,但它没有显示在视图上。
ViewModel1
public class Data1 : INotifyPropertyChanged
{
private string _string1;
public string String1
{
get { return _string1; }
set { _string1 = value; onPropertyChnaged("String1"); }
}
private void onPropertyChnaged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
ViewModel2
public class Data2 : INotifyPropertyChanged
{
private string _string2;
public string String2
{
get { return _string2; }
set { _string2 = value; onPropertyChnaged("String2");}
}
private void onPropertyChnaged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
观看次数:
public partial class MainWindow : Window
{
Data12 d12 = new Data12 { };
public MainWindow()
{
InitializeComponent();
DataContext = d12;
}
private void button_Click(object sender, RoutedEventArgs e)
{
ViewModel_1();
ViewModel_2();
}
private void ViewModel_1()
{
var viewmodel = DataContext as Data12;
viewmodel.Data1.String1 = textBox.Text;
}
private void ViewModel_2()
{
var viewmodel = DataContext as Data12;
viewmodel.Data1.String1 = textBox.Text;
}
}
组合视图模型:
class Data12
{
public Data1 Data1 = new Data1();
public Data2 Data2= new Data2();
}
Xaml 文件:
<Grid>
<Label x:Name="label" HorizontalAlignment="Left" Margin="92,61,0,0" VerticalAlignment="Top" Content="{Binding Data1.String1}" />
<Label x:Name="label1" Content="{Binding Data2.String2}" HorizontalAlignment="Left" Margin="349,61,0,0" VerticalAlignment="Top" />
<TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="65,153,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="textBox1" HorizontalAlignment="Left" Height="23" Margin="360,153,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
<Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="205,246,0,0" VerticalAlignment="Top" Width="75" Click="button_Click" />
</Grid>
没有 Nullreference,但绑定不起作用。我什至尝试通过实例化内部属性,但没有奏效。请帮助我。
【问题讨论】:
-
为什么要降级?
-
Data12在哪里? -
查看输出窗口是否有绑定错误。 WPF 绑定因吞下异常和错误并将它们隐藏在输出窗口中而臭名昭著。
-
抱歉错过了添加抱歉
标签: c# wpf xaml mvvm datacontext