因此,正如在前面的问题中提到的那样,我问来自UserControl的WPF数据绑定,我已经成功地基于DependencyProperty在文件后面的UserControls代码内的值绑定了Control的TabHeader,并使用INotifyPropertyChanged实现了类似的实现。
但是,现在我需要它来处理UserControls ViewModel中的值。我可以使用INotifyPropertyChanged成功更新UserControl UI,但由于似乎使它变色,因此无法将此值绑定到主窗口中的TabItem控件。
这甚至可能还是我在错误的树上吠叫吗?
主窗口(TabControl)<---> UserControl <---> ViewModel
MainWindow.xaml
<Grid>
<TabControl Height="250" HorizontalAlignment="Left" Margin="12,26,0,0" Name="tabControl1" VerticalAlignment="Top" Width="479">
<TabControl.Resources>
<Style TargetType="TabItem" x:Key="tab1ItemHeaderStyle" >
<Setter Property="HeaderTemplate" >
<Setter.Value>
<DataTemplate DataType="{x:Type TabItem}">
<StackPanel Orientation="Horizontal">
<Label Content="{Binding Path=Header, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=TabItem}}"/>
<Label Content="{Binding Path=SomeFigureVM, ElementName=uc1}"/>
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</TabControl.Resources>
<TabItem Style="{StaticResource tab1ItemHeaderStyle}" Header="[Tab 1]" Name="tabItem1">
<vw:UserControl1 x:Name="uc1"></vw:UserControl1>
</TabItem>
</TabControl>
</Grid>
UserControl1.xaml
<Grid>
<Label Height="43" HorizontalAlignment="Left" Margin="69,128,0,0" Name="textBlock" Content="{Binding SomeFigureVM}" VerticalAlignment="Top" Width="100" />
<Button Name="updateSomeFigure" Content="Update.." Click="updateSomeFigure_Click" Width="100" Height="100" Margin="69,12,66,71" />
</Grid>
UserControl1.xaml.cs
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
this.DataContext = new MyViewModel();
}
private void updateSomeFigure_Click(object sender, RoutedEventArgs e)
{
MyViewModel viewmodel = this.DataContext as MyViewModel;
viewmodel.UpdateFigure();
}
}
MyViewModel.cs
public class MyViewModel: INotifyPropertyChanged
{
public MyViewModel()
{
this.SomeFigureVM = 23;
}
private int _someFigure;
public int SomeFigureVM
{
get
{
return _someFigure ;
}
set
{
_someFigure = value;
NotifyPropertyChanged("SomeFigureVM");
}
}
public void UpdateFigure()
{
SomeFigureVM = SomeFigureVM + 1;
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
一如既往,任何帮助都将不胜感激,我觉得我的头撞在砖墙上!
SomeFigureVM是您的属性MyViewModel
,它是DataContext
for UserControl1
。您正在尝试访问UserControl上的SomeFigureVM属性,该属性不存在。
更改此行:
<Label Content="{Binding Path=SomeFigureVM, ElementName=uc1}"/>
至
<Label Content="{Binding Path=DataContext.SomeFigureVM, ElementName=uc1}"/>
要捕获这样的数据绑定错误,请在调试模式下运行应用程序,并在输出窗口中查看任何数据绑定问题。您的原始代码会产生数据绑定错误,例如:
System.Windows.Data错误:40:BindingExpression路径错误:在'object''UserControl1'(Name ='uc1')'上找不到'SomeFigureVM'属性。BindingExpression:Path = SomeFigureVM; DataItem ='UserControl1'(Name ='uc1'); 目标元素是'标签'(名称=''); 目标属性为“内容”(类型为“对象”)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句