2011-02-15 108 views
1

如何将视图模型中的数据绑定到用户控件资源中的对象?这是一个很抽象的例子:将资源绑定到视图模型

<UserControl ... 
      xmlns:local="clr-namespace:My.Local.Namespace" 
      Name="userControl"> 
    <UserControl.Resources> 
     <local:GroupingProvider x:Key="groupingProvider" GroupValue="{Binding ???}" /> 
    </UserControl.Resources> 

    <Grid> 
     <local:GroupingConsumer Name="groupingConsumer1" Provider={StaticResource groupingProvider"} /> 
     <local:GroupingConsumer Name="groupingConsumer2" Provider={StaticResource groupingProvider"} /> 
    </Grid> 
</UserControl> 

如何绑定GroupValue在这个观点背后的视图模型的属性。我试过以下内容:

<local:GroupingProvider x:Key="groupingProvider" GroupValue="{Binding ElementName=userControl, Path=DataContext.Property}"/> 

但是这不起作用。

编辑:

GroupProvider延伸DependencyObjectGroupValueDependencyProperty的名称。我收到以下错误:

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=DataContext.Property; DataItem=null; target element is 'GroupingProvider' (HashCode=47478197); target property is 'GroupValue' (type 'TimeSpan') 

这似乎表明,它不能找到userControl

更多编辑:

任何人都没有回答我的问题吗?有没有办法做到这一点?

+0

你有没有解决过这个问题?如果是的话,你会介意分享吗? – ZoolWay 2015-04-15 21:25:58

回答

0

为了使结合,GroupingProvider需要从FreezableFrameworkElementFrameworkContentElementGroupValue需要推导为一个DependencyProperty

+0

`GroupProvider`扩展了`DependencyObject`,`GroupValue`是`DependencyProperty`的名字。我相信绑定只需要扩展`DependencyObject`;我试着改成`FrameworkElement`,但它没有工作。阅读我上面的编辑。问题似乎是从资源内引用数据上下文。 – Jordan 2011-02-16 15:43:24

1

我知道它有点晚,但我有同样的问题。里克斯答案是对的,你需要继承Freezable

下面的代码给了我同样的错误,你有

不工作资源:

public class PrintBarcodesDocumentHelper : DependencyObject 
{ 
    public IEnumerable<BarcodeResult> Barcodes 
    { 
     get { return (IEnumerable<BarcodeResult>)GetValue(BarcodesProperty); } 
     set { SetValue(BarcodesProperty, value); } 
    } 

    public static readonly DependencyProperty BarcodesProperty = 
     DependencyProperty.Register("Barcodes", typeof(IEnumerable<BarcodeResult>), typeof(PrintBarcodesDocumentHelper), new PropertyMetadata(null, HandleBarcodesChanged)); 

    private static void HandleBarcodesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    { 
     // Do stuff 
    } 
} 

的XAML:

<UserControl.Resources> 
    <Barcodes:PrintBarcodesDocumentHelper x:Key="docHelper" Barcodes="{Binding BarcodeResults}"/> 
</UserControl.Resources> 

我的视图模型绑定到UserControlDataContext

错误:

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=BarcodeResults; DataItem=null; target element is 'PrintBarcodesDocumentHelper' (HashCode=55335902); target property is 'Barcodes' (type 'IEnumerable`1') 

工作资源类:

public class PrintBarcodesDocumentHelper : Freezable 
{ 
    // Same properties 

    protected override Freezable CreateInstanceCore() 
    { 
     return new PrintBarcodesDocumentHelper(); 
    } 
} 

不幸的是,我不知道为什么它必须是一个Freezable