【发布时间】:2013-12-13 00:59:09
【问题描述】:
所以正如我之前问过WPF Data Binding From UserControl 的问题中提到的那样,我已经使用 DependencyProperty 根据我的 UserControls 代码隐藏文件中的值成功绑定了我的控件的 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));
}
}
}
与往常一样,非常感谢任何帮助,我觉得我一直在用头撞到这块砖墙上!
【问题讨论】:
-
Do not hardcode the DataContext into a UserControl。它破坏了 WPF 的最大好处之一,即拥有单独的 UI 和数据层。如果你有兴趣,我有一篇博客文章可以帮助你更好地理解 WPF 的
DataContext:What is this "DataContext" you speak of? -
感谢您的链接!非常好的建议!
标签: wpf user-controls tabcontrol wcf-binding wpf-4.0