LinkBut​​ton无法运行Silverlight

时间:2011-08-26 22:39:38

标签: c# silverlight

我有一个方法,我打电话来创建一个链接按钮。但问题是,它将实际字段传递给链接按钮的字段名称,因为它给了我一个死链接。

这是方法:

     private static DataGridTemplateColumn CreateHyperlink(string fieldName)
    {
        DataGridTemplateColumn column = new DataGridTemplateColumn();

        column.Header = "";

        string link = @"http://www.amazon.com/gp/product/" + fieldName;

        StringBuilder sb = new StringBuilder();
        sb.Append("<DataTemplate ");
        sb.Append("xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' ");
        sb.Append("xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' ");
        sb.Append("xmlns:src='clr-namespace:Silverlight1.Classes;assembly=Silverlight1.Classes'>");
        sb.Append("<HyperlinkButton ");
        sb.Append("TargetName= '_blank' ");
        sb.Append("Content = 'Link' ");
        sb.Append("NavigateUri =" +"'"+ link +"'");
        sb.Append(" />");
        sb.Append("</DataTemplate>");

        column.CellTemplate = (DataTemplate)XamlReader.Load(sb.ToString());
        column.IsReadOnly = false;
        return column;
    }

这是由

调用的

dgOrder.Columns.Add(CreateHyperlink("asin"));

从WCF Silverlight启用数据服务中获取哪些内容。 如何传递内容而不是字段名称?

1 个答案:

答案 0 :(得分:1)

您没有传递内容,您传递了字段名称,但创建了Binding。您还需要IValueConverter的实现。

让我们从IValueConverter开始,你需要一些带有“字段”字符串值的东西(我假设你指的是绑定到行的对象的 Property 在网格中)并在其前面添加@"http://www.amazon.com/gp/product/"以形成完整的网址。

public class UrlPrefixConverter : IValueConverter
{
     public string Prefix {get; set;}
     public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value != null)
        { 
            return new Uri(Prefix + value.ToString(), UriKind.Absolute);
        }
        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

在App.xaml中放置一个这样的实例: -

 <Application.Resources>
      <local:UrlPrefixConverter Prefix="http://www.amazon.com/gp/product/" x:Key="AmazonPrefixConverter" />
 </Application.Resources>

现在您的create方法如下所示: -

    private static DataGridTemplateColumn CreateHyperlink(string fieldName)
    {
        DataGridTemplateColumn column = new DataGridTemplateColumn();

        column.Header = "";

        string template = @"<DataTemplate
                xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" >
                <HyperlinkButton TargetName=""_blank"" Content=""Link""
                     NavigateUri=""{{Binding {0}, Converter={{StaticResource AmazonPrefixConverter}}}}"" />
             </DataTemplate>"; 

        column.CellTemplate = (DataTemplate)XamlReader.Load(String.Format(template, fieldName));
        column.IsReadOnly = false;
        return column;
    }