【问题标题】:Cannot find source for binding with reference无法通过参考找到绑定源
【发布时间】:2011-05-24 12:57:33
【问题描述】:

我想将 MultiDataTrigger.Conditions 绑定到单选按钮,但它不起作用。这是我的场景。

在 wpf 中,我有一个 GridPanel,假设其中有单选按钮。

我在 GridPanel 中生成动态单选按钮,如下所示:

RadioButton allAccountBtn = new RadioButton();
allAccountBtn.Name = "allAccountBtn";
GridPanel.Children.Add(allAccountBtn);

然后在我的 xaml 中,我有一个图像按钮,该按钮将根据此单选按钮选择和另一个控件的属性进行更改。

这是我的代码:

<Button>
 <Button.Template>
        <ControlTemplate>
               <Image Name="addFolderIcon" Source="Icon/Decoration/folderColor.png">
               <ControlTemplate.Triggers>
                       <MultiDataTrigger>
                             <MultiDataTrigger.Conditions>
                                    <Condition Binding="{Binding Tag, ElementName=folderBackBtn}" Value="{x:Null}"/>
                                    <Condition Binding="{Binding IsChecked, ElementName=allAccountsBtn}" Value="True"/>
                             </MultiDataTrigger.Conditions>
                             <Setter Property="Control.IsEnabled" Value="False"/>
                             <Setter TargetName="addFolderIcon" Property="Source" Value="Icon/Decoration/folder.png"/>
                       </MultiDataTrigger>
               </ControlTemplate.Triggers>
         </ControlTemplate>
 </Button.Template>
</Button>

当我运行程序时,它显示错误代码:“找不到与引用绑定的源”,第二个条件返回 false(elementName=allAccountsBtn)

为什么会这样?

我可以通过任何方式引用从动态命名和生成的 RadioButton 中获取 IsChecked 属性吗?

【问题讨论】:

  • 如果我在我的xaml中添加单选按钮,它可以被检测到,所以现在的问题是,ElementName找不到动态生成的控件。

标签: wpf radio-button datatrigger elementname


【解决方案1】:

我注意到您将动态生成的对象上的 Name 属性设置为“allAccountBtn”(单数“Account”),但您的 XAML 的 ElementName 引用了“allAccountsBtn”(复数“Accounts”)。尝试将它们更改为相同。

【讨论】:

    【解决方案2】:

    让我们本地化问题。 尝试直接在 XAML 中将 RadioButton 添加到您的 GridPanel,而不是在 C# 中。 如果错误仍然存​​在,则问题不在于添加控件的动态方式。

    我认为模板下控件的“可见性”存在问题。您可以调用 yourButton.ApplyTemplate() 来强制构建可视化树。但不确定在 XAML 中是如何完成的。

    【讨论】:

    • 是的,问题是动态生成的 RadioButton。我在本地添加 RadioButton,它运行没有错误。我在调用 GridPanelChildren.Add(allAccountsBtn) 之后调用 GridPanel.ApplyTemplate(),没有任何反应。 allAccountsBtn.ApplyTemplate() 也是如此...我必须动态包含 RadioButton,因为数据来自数据库。
    • 从某处读取,动态生成的控件与本地控件有不同的命名空间,但我不知道如何处理这个线索..
    猜你喜欢
    • 1970-01-01
    • 2016-01-12
    • 2016-04-08
    • 2018-04-01
    • 2011-10-21
    • 2013-03-07
    • 2013-11-10
    • 2020-05-14
    • 1970-01-01
    相关资源
    最近更新 更多