无法找到与引用绑定的源。

4

我希望将我的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>

当我运行该程序时,它显示错误代码:“无法找到引用绑定的源”,第二个条件(elementName = allAccountsBtn)返回false。
为什么会发生这种情况?
有没有方法可以引用动态命名和生成的RadioButton的IsChecked属性?

如果我在XAML中添加单选按钮,它可以被检测到,所以现在的问题是,ElementName无法找到动态生成的控件。 - VHanded
2个回答

2

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


1

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

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


是的,问题在于动态生成的RadioButton。我本地添加了RadioButton,它运行时没有错误。在我调用GridPanelChildren.Add(allAccountsBtn)之后,我调用GridPanel.ApplyTemplate(),但什么也没发生。allAccountsBtn.ApplyTemplate()也是一样...我必须动态包含RadioButton,因为数据来自数据库。 - VHanded
从某个地方读取,动态生成的控件具有不同的命名空间与本地控件,但我不知道如何处理这个线索。 - VHanded

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接