在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/