2011-02-15 109 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