【发布时间】:2018-01-23 18:36:01
【问题描述】:
我有一个 DataGrid,这个 DataGrid 的一部分是几个带有可切换选项的列。这些可切换的选项显示为图像,如果选项为“真”,则为彩色,如果选项为“假”,则显示为灰色。每个 Image 都有一个 MouseDown 事件,行中带有一个转换器,结构最终如下所示:
当前结构:
...
<DataGridTemplateColumn Header="" Width="20" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding Converter={StaticResource Option1Converter}}" MouseDown="Option1_MouseDown" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="" Width="20" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding Converter={StaticResource Option2Converter}}" MouseDown="Option2_MouseDown"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="" Width="20" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding Converter={StaticResource Option3Converter}}" MouseDown="Option3_MouseDown" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
...
MouseDown 事件的处理方式如下。我只需在行中找到主键即可轻松识别该行。我在这里不知道该怎么做实际上是在此行和列处切换图像。我想能够说'Image.Source at this row/column = thisImage',但我不确定如何实际实现这一点。 MouseDown 事件在这里:
private void Option1_MouseDown(object sender, MouseEventArgs e)
{
var dc = (sender as System.Windows.Controls.Image).DataContext;
DataRowView row = (DataRowView) dc;
String URL = Convert.ToString(row.Row["ID"]);
int newState = myQuery.UpdateIsTogglable(rowID);
if (newState)
// Toggle the image at this row. <-- This is the end goal!
else
// Toggle the image at this row.
}
实际值是来自数据库的 int。加载 Datagrid 时,转换器会处理实际的初始状态:
public class PostIconConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
ImageSource result = null;
//var intValue = (int)value;
DataRowView rawRows = (DataRowView) value;
DataRow row = (DataRow) rawRows.Row;
int intValue = row.Field<Int32>("Option1");
switch (intValue)
{
case 0:
{
result = new BitmapImage(new Uri(@"/myProject;component/Images/Option1_false.png", UriKind.Relative));
break;
}
case 1:
{
result = new BitmapImage(new Uri(@"/myProject;component/Images/Option1_true.png", UriKind.Relative));
break;
}
}
return result;
}
}
现在,我尝试为该行实际分配一个 int 值,但 Converter 实际上并没有按照我希望的方式翻转它。这是我的非工作尝试:
// This doesn't work :(
private void Option1_MouseDown(object sender, MouseEventArgs e)
{
var dc = (sender as System.Windows.Controls.Image).DataContext;
DataRowView row = (DataRowView) dc;
String URL = Convert.ToString(row.Row["ID"]);
int newState = myQuery.UpdateIsTogglable(rowID);
if (newState)
row.Row["Option1"] = 1;
else
row.Row["Option1"] = 0;
}
目标:
我需要能够在点击时切换这些图标的图像源。当我单击它时,我不确定我需要做什么才能从数据网格中获取特定的图像控件。有什么简单的方法可以做到这一点?我可以通过列索引或名称以某种方式实现这一点吗?
【问题讨论】: