如何从 C# 代码生成此 xaml:
目前:
<TextBlock>
Click <Hyperlink Command="{Binding MyCommand}">here</Hyperlink> to continue.
</TextBlock>
我想要的:
<TextBlock Text="{Binding MyTextWithHyperlink, Mode=OneWay}" />
public string MyTextWithHyperlink
{
get
{
return ""; //???
}
}
更新:这就是我要返回字符串的原因,因为 IDataError 返回一个字符串...
String IDataError.this[String columnName]
{
get
{
if (columnName == "MyProperty")
{
if (something1) return ""; //????
if (something2) return "some other string";
}
return null;
}
}
最佳答案
不幸的是,没有简单的方法来做到这一点......据我所知,你能做的最好的事情就是返回一个 XAML 字符串并使用转换器来解析它。
警告:前面的代码丑陋...
XAML
<Window.Resources>
<local:XamlToTextBlockConverter x:Key="xamlConverter" />
</Window.Resources>
<Grid>
<ContentControl Content="{Binding MyTextWithHyperlink, Converter={StaticResource xamlConverter}}" />
</Grid>
转换器
public class XamlToTextBlockConverter : IValueConverter
{
#region Implementation of IValueConverter
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string xaml = value as string;
if (xaml == null)
return Binding.DoNothing;
const string textBlockFormat =
@"<TextBlock xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"">{0}</TextBlock>";
string fullXaml = string.Format(textBlockFormat, xaml);
return (TextBlock)XamlReader.Parse(fullXaml);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
View 模型
public string MyTextWithHyperlink
{
get { return "Click <Hyperlink Command=\"{Binding MyCommand}\">here</Hyperlink> to continue"; }
}
请注意使用 ContentControl
而不是 TextBlock
:这是因为 TextBlock.Text
属性只能包含纯文本,不能包含格式化文档,并且 Inlines
属性无法绑定(bind),因为它不是依赖属性(无论如何它是只读的)。相反,我们在转换器中手动创建一个 TextBlock
并将其分配给 ContentControl
的内容。
这绝对不是一个非常优雅的解决方案,但它确实有效......
https://stackoverflow.com/questions/5953499/