[英]How to Dynamically change Datagrid Columns in xaml
使用WPF DataGrid,我希望能夠基於ViewModel的屬性來更改xaml中顯示的列。
想法只是根據ViewModel的屬性更改列集。 各個視圖的列以不同的組合且順序不同。
我認為這應該是微不足道的,但是我找不到以前在哪里完成此操作的示例
任何幫助,將不勝感激。 謝謝。
最簡單的是:
Xaml
<Window
x:Class="Sample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Height="350"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Width="700">
<Window.Resources>
</Window.Resources>
<Grid>
<DataGrid
x:Name="grid"
ItemsSource="{Binding Persons}"
AutoGenerateColumns="False">
<!-- If Mode = City then
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
<DataGridTextColumn Header="City" Binding="{Binding FavouriteCity}"/>
</DataGrid.Columns>
-->
<!-- If Mode = Colour then -->
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
<DataGridTextColumn Header="Colour" Binding="{Binding FavouriteColour}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
碼
namespace Sample {
public partial class MainWindow: INotifyPropertyChanged
{
public ObservableCollection<Person> Persons { get; set; }
public string Mode { get; set; }
public MainWindow() {
InitializeComponent();
Persons = new ObservableCollection<Person>()
{ new Person("John","Yellow","Paris"),
new Person("Anne","Green","Lagos"),
new Person("James","Pink","Brussels")
};
Mode = "City";
OnPropertyChanged("Persons");
OnPropertyChanged("Mode");
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public class Person
{
public string Name { get; set; }
public string FavouriteColour { get; set; }
public string FavouriteCity { get; set; }
public Person(string name, string favouriteColour, string favouriteCity)
{
Name = name;
FavouriteColour = favouriteColour;
FavouriteCity = favouriteCity;
} } }
我敢肯定有很多方法可以實現,但是我想到的第一件事就是VisualStateManager。 在這里查看MSDN。 您可以先閱讀該頁面底部的摘錄-摘錄:
VisualStateManager使您可以指定控件的狀態,控件在特定狀態時的外觀以及控件更改狀態時的外觀。
需要說明的是,我尚未真正使用過VSM。 我只是在回答另一個人的問題時碰到了它。 您可能會發現他的問題是一個有啟發性的示例: 使用VSM觸發器更改GridView項的高度
但是,此類目的的描述與您的用例匹配,並且您的實現似乎是VSM示例的相對簡單的擴展。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.