【发布时间】:2012-04-24 07:06:32
【问题描述】:
我想从 C# 更改 ScrollViewer 和 ListBox 的属性。
我在 Stackoverflow 上找到了 this question。我接受了已接受答案的建议,并将 ScrollViewer 暴露为子类的属性。但是,这在下面显示的示例中似乎不起作用。该问题中的一些 cmets 还表示该技术无效。
XAML:
<Window x:Class="StackoverflowListBoxScrollViewer.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
</Window>
C#:
using System;
using System.Windows;
using System.Windows.Controls;
namespace StackoverflowListBoxScrollViewer
{
public class MyListBox : ListBox
{
public ScrollViewer ScrollViewer
{ get { return (ScrollViewer)GetTemplateChild("ScrollViewer"); } }
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var myListBox = new MyListBox();
Content = myListBox;
myListBox.Items.Add(new Button() { Content = "abc" });
myListBox.Items.Add(new Button() { Content = "abc" });
myListBox.Items.Add(new Button() { Content = "abc" });
myListBox.Items.Add(new Button() { Content = "abc" });
myListBox.Items.Add(new Button() { Content = "abc" });
var button = new Button() { Content = "Check ScrollViewer" };
button.Click += (s, e) =>
{
if (myListBox.ScrollViewer == null)
Console.WriteLine("null");
};
myListBox.Items.Add(button);
}
}
}
当我单击“检查 ScrollViewer”按钮时,它会打印“null”。即,ScrollViewer 未被检索到。
我怎么去那个该死的ScrollViewer? :-)
【问题讨论】:
-
...您真的不应该将您的 ScrollViewer-Property 称为“ScrollViewer”。
-
@chiffre:为什么不呢?它实际上在 .NET 属性命名指南中:考虑为属性赋予与其类型相同的名称。 (msdn.microsoft.com/en-us/library/ms229012.aspx)
-
@AvnerShahar-Kashtan:引用的链接是关于枚举的。并且仅枚举。你可能会争论这是否是一个好习惯。这只是我的观点,为类型和属性使用相同的名称会让我发疯......
-
我知道它只明确提到了枚举,但我觉得这个想法对其他类型也有好处。我想不出一个比 ScrollViewer 更好的 ListBox 的 ScrollViewer 名称。你可以把它扭来扭去,叫它 ScrollContainer 或 ScrollProvider 或 ScrollPane,但你并没有让它更清楚。
标签: c# wpf xaml listbox scrollviewer