【发布时间】:2018-01-15 05:46:51
【问题描述】:
我有以下 xaml 代码:
<DataGrid CanUserReorderColumns="False"
CanUserResizeColumns="False"
CanUserResizeRows="False"
CanUserSortColumns="False"
SelectionMode="Extended"
SelectionUnit="Cell"
Name="endpoints"
AlternatingRowBackground="LightGray"
AlternationCount="2"
Margin="5"
Height="250"
ScrollViewer.CanContentScroll="True"
ScrollViewer.VerticalScrollBarVisibility="Visible"
ScrollViewer.HorizontalScrollBarVisibility="Disabled">
...
<DataGridTemplateColumn Header="Validate" Width="*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button x:Name="validate" Click="validate_Click">
<Image Source="{Binding validateImage}" Height="16" Width="16"/>
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
我使用 foreachloop 填充 DataGrid 的每一行:
endpoints.Items.Add(new endpointObjects() {... });
validate_Click 函数
private void validate_Click(object sender, RoutedEventArgs e)
{
var currentRowIndex = endpoints.Items.IndexOf(endpoints.CurrentItem);
var currentColIndex = endpoints.CurrentCell.Column.DisplayIndex;
DataGridRow t = dataGridTools.GetRow(endpoints, currentRowIndex);
var ip = (t.Item as endpointObjects).ip;
var port = (t.Item as endpointObjects).port;
MessageBox.Show("Validate Button Clicked: " + currentRowIndex + " | " + currentColIndex + " | "
+ (t.Item as endpointObjects).isHost + " | "
+ " | " + (t.Item as endpointObjects).ip
+ ":" + (t.Item as endpointObjects).port);
}
我似乎无法解决该图像。我希望有如下所示的 Javascript DOM 方法。
[datagrid] > [button name] > [image].Image Source = "images\newImage.png";
endpoints.edit.Image.Source = "images\newImage.png";
因此,当我单击按钮/图像时,它会触发一个函数(在本例中为 validate_Click),该函数执行特定任务并根据该任务的结果将按钮图像更改为另一个图像。
对所有这些都非常陌生,因此非常感谢任何帮助我了解我哪里出错的帮助。
更新 - 已解决
这已通过以下 2 行解决:
var image = (Image)(sender as Button).Content;
image.Source = new BitmapImage(new Uri("images/tick.png", UriKind.RelativeOrAbsolute));
基本功能实现示例如下:
private void validate_Click(object sender, RoutedEventArgs e)
{
var currentRowIndex = endpoints.Items.IndexOf(endpoints.CurrentItem);
var currentColIndex = endpoints.CurrentCell.Column.DisplayIndex;
DataGridRow t = dataGridTools.GetRow(endpoints, currentRowIndex);
var ip = (t.Item as endpointObjects).ip;
var port = (t.Item as endpointObjects).port;
var image = (Image)(sender as Button).Content;
image.Source = new BitmapImage(new Uri("images/tick.png", UriKind.RelativeOrAbsolute));
MessageBox.Show("Validate Button Clicked: " + currentRowIndex + " | " + currentColIndex + " | "
+ (t.Item as endpointObjects).isHost + " | "
+ (t.Item as endpointObjects).FTRname
+ " | " + (t.Item as endpointObjects).ip
+ ":" + (t.Item as endpointObjects).port
+ " | " + image.Source.ToString()
);
}
【问题讨论】:
-
你可以使用转换器来做到这一点。检查以下示例代码。