2014-11-03 42 views
0
  1. 我有个用户控件(UC1),其具有的数据上下文:ViewModelOne。
  2. 我有一个使用UC1作为子控件的MainWindow应用程序。
  3. 这个MainWindow也有一个数据上下文:ViewModelTwo。

极品属性在视图模型的数据上下文标记声明绑定,就像这样:'绑定到从在主窗口中的数据上下文子控制的ViewModels属性主窗口DataContext属性视图模型标记

<Window x:Class="control.controlnamespace" 
xmlns:vm="clr-namespace"..> 
<Window.DataContext> 
*<vm:ViewModelTwo Property="{Binding SomeProperty, ElementName=myControl}"/>* <-- Issue Here 
</Window.DataContext> 

<Grid> 
    <UC1 x:Name="myControl"/> 
</Grid> 

这就是我有没有更新发生的故障,并结合不发生任何。

+0

我还不清楚你的问题。你能用一个例子来解释吗? – Vishal 2014-11-03 18:29:40

+0

看来,我设置在数据上下文级别的属性 Property =“{Binding SomeProperty,ElementName = myControl}”/> – varitomiranda 2014-11-03 19:22:28

回答

0

我发现这个解决方案:

设置或试图设置窗口的datacontext标记内的视图模型的申报财产是错误的,不会有任何影响。这是因为当这个上下文被设置时,它在不同的线程下,因此没有更新或更改被通知。

错--->

<Window.DataContext> 
<vm:ViewModelTwo Property="{Binding SomeProperty, ElementName=myControl}"/>* <-- Issue Here 
</Window.DataContext> 

所以要解决这个是实际获得当前加载元素的方法(这可能是用户控制窗口等) 正确 - >

<Window Name="myWindowName"> 
    <Window.DataContext> 
     <vm:ViewModel /> 
    </Window.DataContext> 

    <control:Control x:Name="myControl" PropertyToBind="{Binding Path=DataContext.Property, Mode=TwoWay, ElementName=myWindowName or myUserControlName}" > 
</Window> 
0

我不知道,但尝试这个办法:

在你MainWindow.xaml:

<Window ........ > 
    <Window.DataContext> 
     <vm:ViewModelOne /> 
    </Window.DataContext> 
</Window> 

在你ViewModelOne:

public class ViewModelOne : INotifyPropertyChanged 
{ 
    ..... 
    ..... 

    private string _UCText; 
    public string UCText 
    { 
     get 
     { 
      return _UCText; 
     } 
     set 
     { 
      _UCText = value; 
      OnPropertyChanged("UCText"); 
     } 
    } 

    // Implement INotifyPropertyChanged 
    ..... 
    ..... 
} 

在你的用户控件:

<UserControl ...... > 
    <UserControl.DataContext> 
     <vm:ViewModelTwo /> 
    </UserControl.DataContext> 

    <TextBlock Text="{Binding Path=DataContext.UCText, 
           RelativeSource={RelativeSource Mode=FindAncestor 
                  AncestorType={x:Type Window}}}" /> 

</UserControl> 

如果您有任何问题上面的代码然后随意问。

+0

如果不是绑定到文本框,而是将其绑定到属性内部ViewModelTwo像这样:vm:ViewModelTwo Property = {Binding Path = UCText,RelativeSource = {RelativeSource Mode = FindAncestor ... – varitomiranda 2014-11-03 21:09:20

+0

我不明白你的意思。但是我的理解是你想要在ViewModelTwo中的属性中获得UCText的值(在ViewModelOne中声明).. Right ????? – Vishal 2014-11-03 21:14:06

+0

是啊!这就是我想要完成的。不知道我能否做到这一点。 – varitomiranda 2014-11-03 23:32:00

相关问题