在我的應用程序中,我想要一個下拉框來選擇要編輯的表格(約20個)。每個表都應該由其自己的WPF DataGrid表示。 (我想過使用單個DataGrid並在運行時創建一組新的列,並使用代碼隱藏功能,但這看起來不太符合XAML-ish。)指定要在運行時顯示的幾個WPF DataGrid中的一個
我的下拉列表位於UserControl中它是更大的應用程序的一部分)。我相信(從我的研究),對單的-20的DataGrid中的佔位符應作爲一個佔位符這裏ContentControl中:
<UserControl x:Class="MyClass" ...
xmlns:my="clr-namespace:MyNamespace"
DataContext="{Binding ViewModel}">
<StackPanel>
<Grid>
<ComboBox Name="DataPaneComboBox" HorizontalAlignment="Stretch"
IsReadOnly="True" MinWidth="120"
Focusable="False" SelectedIndex="0"
DockPanel.Dock="Left" Grid.Column="0"
SelectionChanged="DataPaneComboBox_SelectionChanged">
<ComboBoxItem Name="FirstOption" Content="Choice 1" />
<ComboBoxItem Name="SecondOption" Content="Choice 2" />
<ComboBoxItem Name="ThirdOption" Content="Choice 3" />
</ComboBox>
</Grid>
<ContentControl Name="DataGridView" Margin="0,3,0,3" Content="{Binding CurrentView}" />
</StackPanel>
這裏是我的代碼隱藏這個類:
public partial class MyClass : UserControl {
private MyViewModel ViewModel {
get; set;
}
public MyClass() {
InitializeComponent();
ViewModel = new MyViewModel();
ViewModel.CurrentView = new DataGridChoice1();
}
}
而且視圖模型(類ObservableObject實現INotifyPropertyChanged接口):
public class MyViewModel : ObservableObject {
private UserControl _currentView;
public UserControl CurrentView {
get {
if (this._currentView == null) {
this._currentView = new DatGridChoice1();
}
return this._currentView;
}
set {
this._currentView = value;
RaisePropertyChanged("CurrentView");
}
}
#endregion
}
而20個左右的用戶控件可以在運行時被取代在之一:
<UserControl x:Class="Choice1Control"
xmlns:my="clr-namespace:MyNamespace">
<DataGrid ItemsSource="{Binding Choice1Objects}" />
<!-- ... -->
</DataGrid>
</UserControl>
當用戶改變下拉我想程序加載適當的數據網格。現在我看不到子UserControl(在這裏,Choice1Control
)。我直接添加了孩子(沒有介入的ContentControl),並且它工作正常。
我已經嘗試過幾乎所有DataContext和UserControl內容綁定的組合。我對WPF很陌生,所以我可能錯過了一些顯而易見的東西。謝謝!
你在哪裏指定你的代碼中的數據源,即ViewSource ..等等......? – MethodMan 2012-02-15 21:53:31
你是什麼意思?我的印象是將DataContext設置爲類「ViewModel」,並將ContentControl的內容設置爲指向「CurrentView」就足以指示控件的指定位置。你可以說得更詳細點嗎? – Tenner 2012-02-15 22:04:06
我在Binding方面講的比較多..我看到你使用的是{Binding},但是Binding需要某種源 – MethodMan 2012-02-15 22:05:37