我查看了Treeview綁定的所有示例, 但仍然無法將其與視圖模型中的Treeview綁定。 請讓我知道我在這裏失蹤。樹視圖綁定到視圖模型不起作用
//這是我的類,需要在UI中作爲樹視圖生成。
public class Station
{
public string Name { get; set; } // Header of Treeview
public ObservableCollection<AnalogToDigital> Adc { get; set; }
public ObservableCollection<DigitalToAnalog> Dac { get; set; }
public ObservableCollection<AuxilaryInputs> AuxInput { get; set; }
}
//ADC channel Details
public class AnalogToDigital
{
public string InternalName { get; set; }
}
//DAC channel details
public class DigitalToAnalog
{
public string InternalName { get; set; }
}
//Input output pin details
public class AuxilaryInputs
{
public string InternalName { get; set; }
}
//View.xaml:樹形視圖XAML代碼:
<TreeView Name="StationTree" HorizontalAlignment="Left" Height="326.04" Margin="10,10,0,0"
VerticalAlignment="Top" Width="188" ItemsSource="{Binding StationTree}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding StationTree}">
<TreeViewItem Header="{Binding Name}"/>
<HierarchicalDataTemplate.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding StationTree.Adc}">
<TreeViewItem Header="{Binding StationTree.Adc.InternalName}"/>
</HierarchicalDataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
//視圖模型:我使用mvvmlight這裏
public class MainViewModel : ViewModelBase
{
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
// Move it to business layer
StationXmlOperation stRead = new StationXmlOperation();
StationTree = (Station)stRead.Read(@"C:\Station.xml");
}
private string _name;
private Station _stationTree;
public Station StationTree
{
get { return _stationTree; }
set
{
_stationTree = value;
RaisePropertyChanged(() => StationTree);
}
}
}
//代碼隱藏文件:View.xaml .cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var viewModel = new MainViewModel();
this.DataContext = viewModel;
//this.StationTree.DataContext = viewModel.StationTree;
this.StationTree.Items.Add(viewModel.StationTree);
}
}
// XML文件:Station.xml
<StationDetails>
<Station id="1" Name="FirstStation">
<ADCs>
<ADC id="1" InternalName="ADC1" ></ADC>
<ADC id="1" InternalName="ADC2" ></ADC>
</ADCs>
<DACs>
<DAC id="1" InternalName="DAC1" ></DAC>
<DAC id="1" InternalName="DAC2" ></DAC>
</DACs>
<IOs>
<IO id="1" InternalName="IO1" ></IO>
</IOs>
</Station>
</StationDetails>
//樹形目錄從上述對象分層結構預期是
Name
->ADC
-->InternalName
->DAC
-->InternalName
->AuxInput
-->InternalName
目前代碼僅顯示 「FirstStation」。
請幫助我,我第一次使用treeview。
第一個問題:財產'StationTree在您的視圖模型是不是集合,它僅僅是一個對象:「站」。你正試圖將它綁定到一個ItemsSource,所以它需要是一個集合。 Next:HierarchicalDataTemplates中的ItemsSource綁定是錯誤的。DataContext是構成TreeView綁定的原始集合的各個對象,而不是ViewModel本身。 –
如何將下面的類綁定到Treeview。 'public class station { public string Name {get;組; } // Treeview的標題 public ObservableCollection Adc {get;組; } public ObservableCollection Dac {get;組; } public ObservableCollection AuxInput {get;組; } }' –
Umesh