c# - 为什么默认情况下 WPF 控件不是私有(private)的?

标签 c# wpf

在WPF中,写作

<TextBlock x:Name="foo"/>

将使控件公开。要使其成为 private,必须明确指定 FieldModifier:

<TextBlock x:Name="foo" x:FieldModifier="private"/>

我觉得这很奇怪。我不认为直接从类外部访问子控件是一种好的编码风格。例如,我会避免写

var muc = new MyUserControl();
muc.foo.Text = "foo";

相反,我会编写一个公共(public)方法并使用它:

public void SetFooText(string text) { foo.Text = text; }
// in somewhere else
var muc = new MyUserControl();
muc.SetFooText("foo");

或者写一个公共(public)属性

public string FooText 
{ 
    get { return foo.Text; } 
    set { foo.Text = value; } 
}
// in somewhere else
var muc = new MyUserControl();
muc.FooText = "foo";

因此,我真的看不出将控件默认设置为 public 有什么好处。如果 private 是默认值,可能会更安全,就像 C# 中的所有内容一样。

为什么 public 是默认值?

编辑:

嗯,我错了。正如其他人提到的,默认值为 internal 。但是为什么它不是private的问题还在等待答案。

最佳答案

C# 的 x:FieldModifier 默认值为 NotPublic(Internal)

TypeAttributes.NotPublic is the default behavior because it is infrequent that code outside the assembly that compiled the XAML needs access to a XAML-created element. WPF security architecture together with XAML compilation behavior will not declare fields that store element instances as public, unless you specifically set the x:FieldModifier to allow public access.

如我们所见,如果默认情况下它们是私有(private)的,则编译 XAML 的程序集将无法访问 XAML 创建的元素。

您可以在此处找到更多信息 MSDN

关于c# - 为什么默认情况下 WPF 控件不是私有(private)的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43360497/

相关文章:

c# - 如何调试 "Not enough storage is available to process this command"

c# - 'Service Reference' 和 'Web Reference' 之间的不同行为

c# - Azure 媒体服务从 HTML 上传

c# - 当路径中存在句点时找不到 ServiceStack 处理程序

c# - 了解 WPF - 在模型或 ViewModel 中存储数据

c# - 帮助 C# 中的程序集信息文件

c# - DataGridTemplateColumn 的自定义控件

c# - 使用 TreeView 的主视图/详细 View

c# - Combobox 和 SelectionChanged 问题

wpf - 无法加载文件或程序集 'Microsoft.Windows.Design.Interaction, Version=4.3.0.0, PublicKeyToken=b03f5f7f11d50a3a'