C# WPF TextBlock 中的自动垂直滚动条?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1192335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Automatic vertical scroll bar in WPF TextBlock?
提问by Bab Yogoo
I have a TextBlock
in WPF. I write many lines to it, far exceeding its vertical height. I expected a vertical scroll bar to appear automatically when that happens, but it didn't. I tried to look for a scroll bar property in the Properties pane, but could not find one.
我TextBlock
在 WPF 中有一个。我给它写了很多行,远远超过它的垂直高度。我希望在发生这种情况时会自动出现垂直滚动条,但事实并非如此。我试图在“属性”窗格中查找滚动条属性,但找不到。
How can I make vertical scroll bar created automatically for my TextBlock
once its contents exceed its height?
TextBlock
一旦其内容超过其高度,如何为我自动创建垂直滚动条?
Clarification: I would rather do it from the designer and not by directly writing to the XAML.
澄清:我宁愿从设计者那里做,而不是直接写入 XAML。
采纳答案by Drew Noakes
Wrap it in a scroll viewer:
将其包装在滚动查看器中:
<ScrollViewer>
<TextBlock />
</ScrollViewer>
NOTEthis answer applies to a TextBlock
(a read-only text element) as asked for in the original question.
请注意,此答案适用TextBlock
于原始问题中要求的(只读文本元素)。
If you want to show scroll bars in a TextBox
(an editable text element) then use the ScrollViewer
attached properties:
如果要在TextBox
(可编辑文本元素)中显示滚动条,请使用ScrollViewer
附加属性:
<TextBox ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.VerticalScrollBarVisibility="Auto" />
Valid values for these two properties are Disabled
, Auto
, Hidden
and Visible
.
对于这两个属性的有效值为Disabled
,Auto
,Hidden
和Visible
。
回答by vince
can use the following now:
现在可以使用以下内容:
<TextBox Name="myTextBox"
ScrollViewer.HorizontalScrollBarVisibility="Auto"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ScrollViewer.CanContentScroll="True">SOME TEXT
</TextBox>
回答by varagrawal
Something better would be:
更好的是:
<Grid Width="Your-specified-value" >
<ScrollViewer>
<TextBlock Width="Auto" TextWrapping="Wrap" />
</ScrollViewer>
</Grid>
This makes sure that the text in your textblock does not overflow and overlap the elements below the textblock as may be the case if you do not use the grid. That happened to me when I tried other solutions even though the textblock was already in a grid with other elements. Keep in mind that the width of the textblock should be Auto and you should specify the desired with in the Grid element. I did this in my code and it works beautifully. HTH.
这可确保文本块中的文本不会溢出并与文本块下方的元素重叠,如果您不使用网格,可能会出现这种情况。当我尝试其他解决方案时,即使文本块已经与其他元素位于网格中,这也发生在我身上。请记住,文本块的宽度应为 Auto,并且您应该在 Grid 元素中指定所需的 with。我在我的代码中做了这个,它工作得很好。哈。
回答by John
<ScrollViewer Height="239" VerticalScrollBarVisibility="Auto">
<TextBox AcceptsReturn="True" TextWrapping="Wrap" LineHeight="10" />
</ScrollViewer>
This is way to use the scrolling TextBox in XAML and use it as a text area.
这是在 XAML 中使用滚动 TextBox 并将其用作文本区域的方法。
回答by ravi saini
You can use
您可以使用
ScrollViewer.HorizontalScrollBarVisibility="Visible"
ScrollViewer.VerticalScrollBarVisibility="Visible"
These are attached property of wpf. For more information
这些是 wpf 的附加属性。想要查询更多的信息
http://wpfbugs.blogspot.in/2014/02/wpf-layout-controls-scrollviewer.html
http://wpfbugs.blogspot.in/2014/02/wpf-layout-controls-scrollviewer.html
回答by Contango
This answer describes a solution using MVVM.
此答案描述了使用 MVVM 的解决方案。
This solution is great if you want to add a logging box to a window, that automatically scrolls to the bottom each time a new logging message is added.
如果您想将日志框添加到窗口,则此解决方案非常有用,每次添加新的日志消息时,该窗口都会自动滚动到底部。
Once these attached properties are added, they can be reused anywhere, so it makes for very modular and reusable software.
一旦添加了这些附加属性,它们就可以在任何地方重用,因此它构成了非常模块化和可重用的软件。
Add this XAML:
添加此 XAML:
<TextBox IsReadOnly="True"
Foreground="Gainsboro"
FontSize="13"
ScrollViewer.HorizontalScrollBarVisibility="Auto"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ScrollViewer.CanContentScroll="True"
attachedBehaviors:TextBoxApppendBehaviors.AppendText="{Binding LogBoxViewModel.AttachedPropertyAppend}"
attachedBehaviors:TextBoxClearBehavior.TextBoxClear="{Binding LogBoxViewModel.AttachedPropertyClear}"
TextWrapping="Wrap">
Add this attached property:
添加此附加属性:
public static class TextBoxApppendBehaviors
{
#region AppendText Attached Property
public static readonly DependencyProperty AppendTextProperty =
DependencyProperty.RegisterAttached(
"AppendText",
typeof (string),
typeof (TextBoxApppendBehaviors),
new UIPropertyMetadata(null, OnAppendTextChanged));
public static string GetAppendText(TextBox textBox)
{
return (string)textBox.GetValue(AppendTextProperty);
}
public static void SetAppendText(
TextBox textBox,
string value)
{
textBox.SetValue(AppendTextProperty, value);
}
private static void OnAppendTextChanged(
DependencyObject d,
DependencyPropertyChangedEventArgs args)
{
if (args.NewValue == null)
{
return;
}
string toAppend = args.NewValue.ToString();
if (toAppend == "")
{
return;
}
TextBox textBox = d as TextBox;
textBox?.AppendText(toAppend);
textBox?.ScrollToEnd();
}
#endregion
}
And this attached property (to clear the box):
这个附加属性(清除框):
public static class TextBoxClearBehavior
{
public static readonly DependencyProperty TextBoxClearProperty =
DependencyProperty.RegisterAttached(
"TextBoxClear",
typeof(bool),
typeof(TextBoxClearBehavior),
new UIPropertyMetadata(false, OnTextBoxClearPropertyChanged));
public static bool GetTextBoxClear(DependencyObject obj)
{
return (bool)obj.GetValue(TextBoxClearProperty);
}
public static void SetTextBoxClear(DependencyObject obj, bool value)
{
obj.SetValue(TextBoxClearProperty, value);
}
private static void OnTextBoxClearPropertyChanged(
DependencyObject d,
DependencyPropertyChangedEventArgs args)
{
if ((bool)args.NewValue == false)
{
return;
}
var textBox = (TextBox)d;
textBox?.Clear();
}
}
Then, if you're using a dependency injection framework such as MEF, you can place all of the logging-specific code into it's own ViewModel:
然后,如果您使用诸如 MEF 之类的依赖项注入框架,您可以将所有特定于日志记录的代码放入它自己的 ViewModel 中:
public interface ILogBoxViewModel
{
void CmdAppend(string toAppend);
void CmdClear();
bool AttachedPropertyClear { get; set; }
string AttachedPropertyAppend { get; set; }
}
[Export(typeof(ILogBoxViewModel))]
public class LogBoxViewModel : ILogBoxViewModel, INotifyPropertyChanged
{
private readonly ILog _log = LogManager.GetLogger<LogBoxViewModel>();
private bool _attachedPropertyClear;
private string _attachedPropertyAppend;
public void CmdAppend(string toAppend)
{
string toLog = $"{DateTime.Now:HH:mm:ss} - {toAppend}\n";
// Attached properties only fire on a change. This means it will still work if we publish the same message twice.
AttachedPropertyAppend = "";
AttachedPropertyAppend = toLog;
_log.Info($"Appended to log box: {toAppend}.");
}
public void CmdClear()
{
AttachedPropertyClear = false;
AttachedPropertyClear = true;
_log.Info($"Cleared the GUI log box.");
}
public bool AttachedPropertyClear
{
get { return _attachedPropertyClear; }
set { _attachedPropertyClear = value; OnPropertyChanged(); }
}
public string AttachedPropertyAppend
{
get { return _attachedPropertyAppend; }
set { _attachedPropertyAppend = value; OnPropertyChanged(); }
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
Here's how it works:
这是它的工作原理:
- The ViewModel toggles the Attached Properties to control the TextBox.
- As it's using "Append", it's lightning fast.
- Any other ViewModel can generate logging messages by calling methods on the logging ViewModel.
- As we use the ScrollViewer built into the TextBox, we can make it automatically scroll to the bottom of the textbox each time a new message is added.
- ViewModel 切换附加属性以控制 TextBox。
- 由于它使用“附加”,因此速度非常快。
- 任何其他 ViewModel 都可以通过调用日志 ViewModel 上的方法来生成日志消息。
- 当我们使用 TextBox 中内置的 ScrollViewer 时,我们可以让它在每次添加新消息时自动滚动到文本框的底部。
回答by Tony Wu
<ScrollViewer MaxHeight="50"
Width="Auto"
HorizontalScrollBarVisibility="Disabled"
VerticalScrollBarVisibility="Auto">
<TextBlock Text="{Binding Path=}"
Style="{StaticResource TextStyle_Data}"
TextWrapping="Wrap" />
</ScrollViewer>
I am doing this in another way by putting MaxHeight in ScrollViewer.
我通过将 MaxHeight 放入 ScrollViewer 以另一种方式执行此操作。
Just Adjust the MaxHeight to show more or fewer lines of text. Easy.
只需调整 MaxHeight 以显示更多或更少的文本行。简单。
回答by dunkleosteus
Dont know if someone else has this problem but wrapping my TextBlock
into a ScrollViewer
somewhow messed up my UI - as a simple workaround I figured out that replacing the TextBlock
by a TextBox
like this one
不知道如果别人有这个问题,但我的包裹TextBlock
成一个ScrollViewer
搞砸了我的UI somewhow -作为一个简单的解决方法我想通了,更换TextBlock
一个TextBox
像这样的
<TextBox Name="textBlock" SelectionBrush="Transparent" Cursor="Arrow" IsReadOnly="True" Text="My Text" VerticalScrollBarVisibility="Auto">
creates a TextBox
that looks and behaves like a TextBlock
with a scrollbar (and you can do it all in the designer).
创建一个具有滚动条的TextBox
外观和行为TextBlock
(并且您可以在设计器中完成所有操作)。
回答by Zuhair
This is a simple solution to that question. The vertical scroll will be activated only when the text overflows.
这是该问题的简单解决方案。只有当文本溢出时才会激活垂直滚动。
<TextBox Text="Try typing some text here " ScrollViewer.VerticalScrollBarVisibility="Auto" TextWrapping="WrapWithOverflow" />
<TextBox Text="Try typing some text here " ScrollViewer.VerticalScrollBarVisibility="Auto" TextWrapping="WrapWithOverflow" />
回答by Scott Bordelon
I tried to to get these suggestions to work for a textblock, but couldn't get it to work. I even tried to get it to work from the designer. (Look in Layout and expand the list by clicking the down-arrow "V" at the bottom) I tried setting the scrollviewer to Visibleand then Auto, but it still wouldn't work.
我试图让这些建议适用于文本块,但无法让它发挥作用。我什至试图从设计师那里得到它。(查看 Layout 并通过单击底部的向下箭头“V”展开列表)我尝试将 scrollviewer 设置为Visible然后是Auto,但它仍然无法正常工作。
I eventually gave up and changed the TextBlock
to a TextBox
with the Readonlyattribute set, and it worked like a charm.
我最终放弃并使用Readonly属性集TextBlock
将其更改为 a ,它就像一个魅力。TextBox