当ContentPresenter的content属性为String类型时,它会自动使用TextBlock作为其子元素。但我需要在我的应用程序中使用所有ContentPresenters来使用名为DynamicTextBlock(Silverlight中用于CharacterTrimming的用户控件)而不是默认的TextBlock控件。
我如何实现这样的目标?
答案 0 :(得分:2)
您好我是WPF程序员。请检查此解决方案是否适用于Silverlight,请试一试并告诉我。 在下面的代码中代替TextBlock(在DataTemplate中)使用你的silverlight文本块名称,让我知道结果。
<Window x:Class="Editable_ComboBox.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<DataTemplate DataType="{x:Type sys:String}" >
<TextBlock Text="{Binding}" TextTrimming="CharacterEllipsis" Background="AliceBlue" Foreground="Red" />
<!--In the above line, Remove the TextBlock and use your silvelight dynamic textblock name-->
</DataTemplate>
</Window.Resources>
<Grid>
<Button Content="Button" HorizontalAlignment="Left" Margin="204,146,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>
</Window>
答案 1 :(得分:0)
让我们面对现实吧。微软已经证实Silverlight是致命的。如果可能的话,你应该跳到WPF。但是,让我试着回答你的问题。在wpf中有一些非常酷的东西,它被称为属性值继承。让我告诉你如何:
public class MyWpfExtension
{
public static bool GetCharacterEllipsis(DependencyObject obj)
{
return (bool)obj.GetValue(CharacterEllipsisProperty);
}
public static void SetCharacterEllipsis(DependencyObject obj, bool value)
{
obj.SetValue(CharacterEllipsisProperty, value);
}
// Using a DependencyProperty as the backing store for CharacterEllipsis. This enables animation, styling, binding, etc...
public static readonly DependencyProperty CharacterEllipsisProperty =
DependencyProperty.RegisterAttached("CharacterEllipsis", typeof(bool), typeof(MyWpfExtension),
new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.Inherits, OnCharacterEllipsisChanged));
private static void OnCharacterEllipsisChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is TextBlock && (bool)e.NewValue)
{
TextBlock tb = (TextBlock)d;
tb.TextTrimming = TextTrimming.CharacterEllipsis;
}
}
}
顺便说一句,这是你可以看到的WPF。我不知道这对你有多大帮助,但你去了。我假设Silverlight也具有此属性值继承。
现在使用:
<StackPanel Background="Blue" local:MyWpfExtension.CharacterEllipsis ="True">
<TextBlock>asdfsadfsadfsadfasdfsadfsadfsadfasdfsadfsadfsadf</TextBlock>
<TextBlock>asdfsadfsadfsadfasdfsadfsadfsadfasdfsadfsadfsadf</TextBlock>
<TextBlock>asdfsadfsadfsadfasdfsadfsadfsadfasdfsadfsadfsadf</TextBlock>
<TextBlock>asdfsadfsadfsadfasdfsadfsadfsadfasdfsadfsadfsadf</TextBlock>
<TextBlock>asdfsadfsadfsadfasdfsadfsadfsadfasdfsadfsadfsadf</TextBlock>
<TextBlock>asdfsadfsadfsadfasdfsadfsadfsadfasdfsadfsadfsadf</TextBlock>
<TextBlock>asdfsadfsadfsadfasdfsadfsadfsadf</TextBlock>
<TextBlock>asdfsadfsadfsadfasdfsadfsadfsadf</TextBlock>
</StackPanel>
或者像这样:
<StackPanel Background="Blue" >
<ContentPresenter local:MyWpfExtension.CharacterEllipsis="True" Content="fasdfasdfsdffasdfasdfsdffasdfasdfsdffasdfasdfsdf"></ContentPresenter>
</StackPanel>
基本上,您可以设置附加属性,并且该属性将继承到所有元素。如果元素是TextBlock,则将设置CharacterElipsis。