2010-10-24 118 views
2

我有一個TreeView,它綁定到名爲RootViewModel的ViewModel,它具有ViewModels集合ChildViewModel,該集合具有ViewModels GrandhChildViewModel的集合。WPF將綁定TextBox文本屬性綁定到TreeView中的特定ViewModel的屬性

我在樹形視圖旁邊有一個文本框。

我想將文本框的文本綁定到所選項目的特定屬性僅當在樹中選擇GrandChildViewModel。如果未選擇GrandChildViewModel,我希望文本框中的文本爲空。我也想這樣做,所以如果在選擇GrandChild時更改TextBox中的文本,它將更新樹視圖中該項目的文本。 (我假設2路視圖模型<之間的結合 - <>文本框和視圖模型 - >樹狀

 
|------------------| 
| - Root   | 
| - Child  |  |---------------------------------| 
|  - GrandChild |  | Selected GrandChild's Property | 
|  - GrandChild |  |---------------------------------| 
|  - GrandChild |       ^
| - Child  |       | 
|  - GrandChild |<----- Selected GrandChild -| 
|     | 
|------------------|

樣品的ViewModels:

public class RootViewModel : INotifyPropertyChanged 
{ 
    public ObservableCollection<ChildViewModel> Children{ get; set; } 
    public bool IsSelected{ get { /* code */ } set { /* code */ OnPropertyChanged("IsSelected"); } 
} 
public class ChildViewModel : INotifyPropertyChanged 
{ 
    public ObservableCollection<GrandChildViewModel> GrandChildren{ get; set; } 
    public bool IsSelected{ get { /* code */ } set { /* code */ OnPropertyChanged("IsSelected"); } 
    public string SomeProperty{ get { /* code */ } set { /* code */ OnPropertyChanged("SomeProperty"); } 
} 
public class GrandChildViewModel : INotifyPropertyChanged 
{ 
    public bool IsSelected{ get { /* code */ } set { /* code */ OnPropertyChanged("IsSelected"); } 
    public bool SomeOtherProperty{ get { /* code */ } set { /* code */ OnPropertyChanged("SomeOtherProperty"); } 
} 

我嘗試的到目前爲止在XAML:

<TextBox> 
    <TextBox.Style> 
     <Style TargetType="TextBox"> 
      <Style.Triggers> 
       &ltDataTrigger Value="True"> 
        <DataTrigger.Binding> 
         <Binding Converter="{StaticResource myConverter}" ElementName="myTreeView" Path="SelectedItem" Mode="TwoWay" /> 
        </DataTrigger.Binding> 
        <DataTrigger.Setters> 
         <Setter Property="Text" Value="{Binding Path=SomeOtherProperty}" /> 
        </DataTrigger.Setters> 
       </DataTrigger> 
      </Style.Triggers> 
     </Style> 
    </TextBox.Style> 
</TextBox>

也試過

<TextBox Text={Binding ElementName=myTreeView, Path=SelectedItem, Converter={StaticResource myConverter}, Mode=TwoWay}" /> 

很多預先感謝。

更新

我發現這是拋出一個異常,因爲上的SelectedItem雙向數據綁定是不允許的。

回答

1

感謝this post我能得到這個工作。我將文本框周圍的StackPanel設置爲綁定到所選項目,然後將文本框綁定到我關心的屬性。

<StackPanel DataContext={Binding ElementName=myTreeView, Path=SelectedItem}"> 
    <TextBox Text={Binding Path=SomeOtherProperty, Mode=TwoWay}" /> 
</StackPanel> 

工程就像一個魅力。

+0

謝謝,正是我一直在尋找的。 – Stef 2012-10-19 13:23:23