[英]Wpf: How can i change the binding path of a gridview column in a listview to another column of a datatable at runtime?
这是一个示例xaml代码:
<listview>
blah blah blah..
......................
<ListView.View>
<GridView>
<GridViewColumn Header="Date" Width="180" DisplayMemberBinding="{Binding Path=Date}" />
<GridViewColumn Header="Status" Width="80" DisplayMemberBinding="{Binding Path=col1}" />
</GridView>
</ListView.View>
</ListView>
在这里,此绑定路径DisplayMemberBinding =“ {Binding Path = Date}
/ *日期是绑定的SQL数据表的列名* /
假设此数据表具有3列-col1,col2和col3。 我想要的是在运行时将列表视图第二列的绑定路径(当前正在绑定到col1)更改为此数据表的col2或col3。 这意味着当我运行程序并单击一个按钮时,列表视图的第二列将自动更改。
C#代码
conn = new SqlCeConnection(constr);
try
{
conn.Open();
string query = "SELECT * FROM " + tablename + "";
cmd = new SqlCeCommand(query, conn);
cmd.ExecuteNonQuery();
SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
DataSet ds = new DataSet(tablename);
da.Fill(ds);
sview.ItemsSource = ds.Tables[0].DefaultView; //sview is the name of listview
da.Update(ds);
conn.Close();
}
不要更改绑定。 使用视图模型:
public class MyModel
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
public class MyViewModel : INotifyPropertyChanged
{
private readonly MyModel _model;
private bool _displayProperty1;
public MyViewModel(MyModel model)
{
_model = model;
}
public bool DisplayProperty1
{
get { return _displayProperty1; }
set
{
_displayProperty1 = value;
OnPropertyChanged("DisplayProperty1");
OnPropertyChanged("PropertyToDisplay");
}
}
public string PropertyToDisplay
{
get
{
return DisplayProperty1 ? _model.Property1 : _model.Property2;
}
}
}
XAML:
<GridViewColumn Header="Status" Width="80" DisplayMemberBinding="{Binding PropertyToDisplay}" />
您可以通过切换按钮或使用常规按钮+命令来更改DisplayProperty1
。 更改时,绑定列的数据源将从一个属性切换到另一个属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.