相关疑难解决方法(0)

WPF 用户控件和名称范围

我一直在玩 WPF 和 MVVM 并注意到一件奇怪的事情。在{Binding ElementName=...}自定义用户控件上使用时,用户控件中根元素的名称似乎在使用该控件的窗口中可见。说,这是一个示例用户控件:

<UserControl x:Class="TryWPF.EmployeeControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:TryWPF"
             Name="root">
  <Grid>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="*" />
      <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
    <TextBlock Grid.Column="0" Text="{Binding}"/>
    <Button Grid.Column="1" Content="Delete"
                Command="{Binding DeleteEmployee, ElementName=root}"
                CommandParameter="{Binding}"/>
  </Grid>
</UserControl>
Run Code Online (Sandbox Code Playgroud)

对我来说看起来很合法。现在,依赖属性DeleteEmployee在代码隐藏中定义,如下所示:

public partial class EmployeeControl : UserControl
{
    public static DependencyProperty DeleteEmployeeProperty
        = DependencyProperty.Register("DeleteEmployee",
                                      typeof(ICommand),
                                      typeof(EmployeeControl));

    public EmployeeControl()
    {
        InitializeComponent();
    }

    public ICommand DeleteEmployee
    {
        get
        {
            return (ICommand)GetValue(DeleteEmployeeProperty);
        }
        set
        {
            SetValue(DeleteEmployeeProperty, value);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这里没有什么神秘的。然后,使用控件的窗口如下所示:

<Window x:Class="TryWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:TryWPF" …
Run Code Online (Sandbox Code Playgroud)

c# wpf xaml scope mvvm

5
推荐指数
1
解决办法
1859
查看次数

标签 统计

c# ×1

mvvm ×1

scope ×1

wpf ×1

xaml ×1