2011-06-10 132 views
0

考慮下面的XAML代碼:WPF綁定通過StaticResouces

<Window.Resources> 
    <System:String x:Key="StringValue"></System:String> 
</Window.Resources> 
    <Grid> 
     <ComboBox Margin="137,101,169,183" ItemsSource="{Binding collection}" SnapsToDevicePixels="True" IsHitTestVisible="true"> 
     <ComboBox.ItemTemplate> 
      <DataTemplate> 
       <StackPanel Orientation="Horizontal"> 
       <CheckBox Command="{Binding CheckCommand}" IsChecked="{Binding IsChecked}" Content="{Binding Name}"/> 
        <TextBlock Text="{StaticResource StringValue}" /> 
       </StackPanel> 
      </DataTemplate> 
     </ComboBox.ItemTemplate> 
    </ComboBox> 
</Grid> 

我想是的文本塊文本綁定到一個靜態的資源,一個數據綁定到視圖模型的值。問題是System.String似乎不允許數據綁定。任何人都知道如何做到這一點?對於上下文來說,TextBlock需要一個不同於其父組合框的itemSource。

謝謝。

+0

你有別名** ** mscorlib程序? 'xmlns:System =「clr-namespace:System; assembly = mscorlib」'沒有錯誤出現。 – 2011-06-10 08:37:24

+0

是的,絃樂很好。 – 2011-06-10 08:37:58

+0

看看我編輯一個可能的包裝類,它允許檢測字符串的更新 – fixagon 2011-06-10 09:17:05

回答

0

要澄清,A System.String沒有依賴項屬性,所以你不能綁定任何東西。我認爲你需要一個轉換器,以便你的TextBlock可以綁定到視圖模型。你有什麼類型的ObservableCollection視圖模型?

編輯如果你只是想簡單的字符串綁定到文本屬性這是錯誤的答案。如果你想綁定到格式化文本,請繼續閱讀。

我以前有這個問題。我想將我的TextBlock綁定到我的屬性中的字符串資源。我最終將TextBlock分類爲BindableTextBlock,並將string的轉換器轉換爲Inline列表。

Question and Answers here.

它可能看起來有點棘手,就必須有一個更簡單的方法。但是,無論何時我需要綁定到某些格式化的文本並且它可以正常工作,我都會多次使用該控件。希望你能從我的工作中受益,並且可能會有所改進。

2

字符串犯規允許綁定,因爲它不是一個DependencyObject的(和犯規執行INotifyPropertyChanged)

,但你爲什麼不只是直接綁定到視圖模型的價值?

,如果你不能綁定到視圖模型(想想的RelativeSource與搜索父類),你可以實現一個包裝(它實現INotifyPropertyChanged得到的對象的變化)

例包裝類:

public class BindWrapper<T> : INotifyPropertyChanged 
{ 
    private T _Content; 
    public T Content 
    { 
     get 
     { 
      return _Content; 
     } 
     set 
     { 
      _Content = value; 
      if (this.PropertyChanged != null) 
       this.PropertyChanged(this, new PropertyChangedEventArgs("Content")); 
     } 
    } 


    #region INotifyPropertyChanged Members 

    public event PropertyChangedEventHandler PropertyChanged; 

    #endregion 
} 

如何實例化和XAML綁定:

<Window.Resources> 
    <local:BindWrapper x:Key="wrapper" x:TypeArguments="System:String"> 
     <local:BindWrapper.Content> 
      <System:String>huuu</System:String> 
     </local:BindWrapper.Content> 
    </local:BindWrapper> 
</Window.Resources> 
<TextBlock Text="{Binding Source={StaticResource wrapper}, Path=Content}" /> 
+0

我不能直接綁定到值,因爲文本塊父(組合框)具有VM內可觀察集合的項目源。它不會允許我從中分離Textblock。 – 2011-06-10 08:41:53

+0

@Darren Young,是ObservableCollection 或ObservableCollection 還是別的? – Jodrell 2011-06-10 08:45:51