I need to be able to pass an unique commands to the hyperlinks that generated from XML in a DataGrid.
I have commands in the code behind that work if I point them directly to the hyperlinks this way.
<Hyperlink Style="{DynamicResource DataGridCellStyleHyperlink}" Command="{x:Static local:MainWindow.LaunchFirstCommand}">
I need to do similar but assigning different commands to each hyperlink inside cells dynamically. All hyperlinks are generated from XML. I belive I need to have some sort of converter that will do it. I have trouble making it work. Any advice is highly appreciated. Thank you in advance.
Here is XMLDataProdider code that generates content inside DataGrid. I tried to pass 'Command' value as a string:
<XmlDataProvider x:Key="MoreInfoDataGridLocal" XPath="MoreInfoTiles/Servers">
<x:XData>
<MoreInfoTiles xmlns="">
<Servers Name="Test1" Status="003" Name2="Connection 2" Status2="assigned" />
<Servers Name="Test2" Status="Not activated" Name2="Address" Status2="test" />
<Servers Name="Test3" Status="Disabled" Name2="Address" Status2="None" Command="x:Static local:MainWindow.LaunchFirstCommand"/>
</MoreInfoTiles>
</x:XData>
</XmlDataProvider>
I can successfully generate the text strings but command is not doing anything. Below is the code where I hook it up to the hyperlink in datagrid:
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate> 开发者_如何学编程
<TextBlock >
<Hyperlink Style="{DynamicResource DataGridCellStyleHyperlink}" Command="{Binding XPath=@Command}" >
<TextBlock Text="{Binding XPath=@Status}" />
</Hyperlink>
</TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
Yes, you will need to use an IValueConverter to translate the string to a command object. Your Command Binding will look like this:
Command="{Binding XPath=@Command, Converter={StaticResource MyStringToCommandConverter}}"
and you will need an instance of the converter created as a resource:
<MyStringToCommandConverter x:Key="MyStringToCommandConverter"/>
Other than that you just need to create the MyStringToCommandConverter (or whatever you name it) class implementing IValueConverter and in the Convert method translate the "value" string into one of your Routed Commands. A simple converter would look something like this:
public class MyStringToCommandConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string commandType = value as String;
if (commandType == "LaunchFirstCommand")
return MainWindow.LaunchFirstCommand;
if (commandType == "OtherCommand")
return MainWindow.OtherCommand;
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new System.NotImplementedException();
}
}
精彩评论