【问题标题】:How to bind to ContentControl.Content's attached property如何绑定到 ContentControl.Content 的附加属性
【发布时间】:2021-12-01 07:36:08
【问题描述】:

我有一个模块化 WPF 应用程序 - Shell、Module1、Module2、Module3。 每个模块都有这样定义的视图:

<UserControl>

    <TextBox x:Name="DefaultControl"/>
    
    <UserControl.Tag>
        <Binding ElementName="DefaultControl"/>
    </UserControl.Tag>
</UserControl>

Shell 有 MainView,它使用 WPFToolkit BusyIndi​​cator 控件。 MainView 是这样定义的:

<Window>
    <xctk:BusyIndicator IsBusy="{Binding ElementName=MainRegion, Path=Content.DataContext.IsBusy}"
                        FocusAfterBusy="{Binding Path=Content.Tag, ElementName=MainRegion}">
                        
        <ContentControl x:Name="MainRegion">
        </ContentControl>
        
    </xctk:BusyIndicator>
</Window>

BusyIndi​​cator.FocusAfterBusy 旨在在 IsBusy 变为 False 时将焦点设置在名为 DefaultControl 的任何视图元素上。 使用 Tag 属性进行绑定时效果很好。 但现在我想为此使用一个名为 DefaultControl (object) 的简单附加属性。 视图变成这样:

<UserControl>

    <TextBox x:Name="DefaultControl"/>
    
    <ext:FocusExtension.DefaultControl>
        <Binding ElementName="DefaultControl"/>
    </ext:FocusExtension.DefaultControl>
</UserControl>

我应该如何更改 BusyIndi​​cator.FocusAfterBusy="{Binding Path=Content.Tag, ElementName=MainRegion}" 中的路径,以绑定到 MainRegion.Content 的附加属性 (DefaultControl)? 附属性:

public static readonly DependencyProperty DefaultControlProperty = DependencyProperty.RegisterAttached(
    "DefaultControl",
    typeof(object),
    typeof(FocusExtension),
    new PropertyMetadata(null));

public static object GetDefaultControl(DependencyObject obj)
{
    return (object)obj.GetValue(DefaultControlProperty);
}

public static void SetDefaultControl(DependencyObject obj, object value)
{
    obj.SetValue(DefaultControlProperty, value);
}

【问题讨论】:

    标签: wpf xaml mvvm


    【解决方案1】:

    试试这个:

    FocusAfterBusy="{Binding Path=Content.(ext:FocusExtension.DefaultControl), 
        ElementName=MainRegion}"
    

    【讨论】:

    • (ext:FocusExtension.DefaultControl) 的 XAML 编辑器显示“属性‘DefaultControl’不可附加到‘对象’类型的元素”。项目编译、运行——但它不像 Tag 那样设置焦点。输出窗口什么也不显示
    • Visual Studio 中的编辑器不够聪明,无法解决这个问题。不过没关系。为什么会设置焦点?这就是绑定到附加属性的方式。
    • IC ...它会设置焦点,嗯,因为 BusyIndi​​cator.FocusAfterBusy 旨在这样做。并且在使用 Tag 时效果很好。其他设置焦点的常用方法不起作用 - DefaultControl 文本框仅获得逻辑焦点。我的猜测是 BusyIndi​​cator 在显示/隐藏后仍然保留它
    • 我看不出您的原始问题与焦点有何关系。你不是在问如何绑定到ContentControl 的Content 的附加属性吗?
    • 我只是在回答你的问题:为什么要设置焦点? :)
    猜你喜欢
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    • 2011-11-01
    • 2011-02-14
    • 1970-01-01
    相关资源
    最近更新 更多