我想让用户在偏好中控制该文本框内的LineBreak元素,以启用/禁用它
<TextBlock Style="{StaticResource TextBlockStyle}" Width="130">
<TextBlock.Inlines>
<Run Text="{Binding Path=Name}" FontWeight="Bold" Foreground="#FF2A4D9E" />
<Run Text="{Binding Path=Price}" FontWeight="Bold" />
<LineBreak />
<Run Text="{Binding Path=Quantity}" Foreground="#99000000" />
</TextBlock.Inlines>
</TextBlock>
答案 0 :(得分:1)
我不相信FlowDocument中有任何方法可以使LineBreak
没有真正中断,除非将其取出。您可以选择切换到使用WPF布局或使用附加属性在LineBreak和空Run之间切换。
使用WPF布局
您可以考虑使用WPF布局。像这样:
<DataTemplate x:Key="Layout1">
<DockPanel>
<TextBlock Text="{Binding Name}" FontWeight="Bold" Foreground="#FF2A4D9E" />
<TextBlock Text="{Binding Price}" FontWeight="Bold" />
<TextBlock Text="{Binding Quantity}" Foreground="#99000000" />
</DockPanel>
</DataTemplate>
<DataTemplate x:Key="Layout2">
<DockPanel>
<DockPanel DockPanel.Dock="Top">
<TextBlock Text="{Binding Name}" FontWeight="Bold" Foreground="#FF2A4D9E" />
<TextBlock Text="{Binding Price}" FontWeight="Bold" />
</DockPanel>
<TextBlock Text="{Binding Quantity}" Foreground="#99000000" />
</DockPanel>
</DataTemplate>
现在,只需切换DataTemplates即可轻松切换布局。
使用绑定自动删除LineBreaks
如果你想通过绑定“隐藏”LineBreak,你可以使用附加的“BecomeLineBreak”属性来执行它,当应用于空的Run并设置为true时,将其删除并用LineBreak替换它。
像魔术一样,你现在有能力写作:
<Run my:LineBreakSwitcher.BecomeLineBreak="{Binding SomeCondition}" />
只要SomeCondition属性为true,您的Run就会变成LineBreak。
以下是代码:
public class LineBreakSwitcher : DependencyObject
{
public static bool GetBecomeLineBreak(DependencyObject obj) { return (bool)obj.GetValue(BecomeLineBreakProperty); }
public static void SetBecomeLineBreak(DependencyObject obj, bool value) { obj.SetValue(BecomeLineBreakProperty, value); }
public static readonly DependencyProperty BecomeLineBreakProperty = DependencyProperty.RegisterAttached("BecomeLineBreak", typeof(bool), typeof(LineBreakSwitcher), new PropertyMetadata
{
PropertyChangedCallback = (obj, e) =>
{
var oldElement = (Inline)obj;
var newElement = (bool)e.NewValue ? (Inline)new LineBreak() : new Run();
newElement.SetBinding(BecomeLineBreakProperty, oldElement.GetBindingExpression(BecomeLineBreakProperty).ParentBindingBase);
var parent = (Paragraph)oldElement.Parent;
parent.Inlines.InsertBefore(oldElement, newElement);
parent.Inlines.Remove(oldElement);
}
});
工作原理:当一个Run上的BecomeLineBreak变为true时,会创建一个新的LineBreak,复制BecomeLineBreak绑定,在Run之前插入LineBreak,然后删除Run。当BecomeLineBreak变为false时,将创建一个新的Run并且整个过程反过来。
答案 1 :(得分:0)
这就是你想要的(100%XAML):
<TextBlock Text="{Binding Text, ElementName=MyContainer}"
FontWeight="Bold" FontSize="14" Name="TextBlockA" />
<TextBlock Name="TextBlockB">
<TextBlock.Style>
<Style>
<Setter Property="TextBlock.Visibility" Value="Visible"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Text.Length,
ElementName=TextBlockC}" Value="0">
<Setter Property="TextBlock.Visibility" Value="Collapsed"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
<LineBreak />
</TextBlock>
<TextBlock Text="{Binding SubText, ElementName=MyContainer}"
FontWeight="Normal" FontSize="12" Name="TextBlockC" />