InvalidOperationException: Specified element is already
the logical child of another element. Disconnect it first.
到目前为止,谷歌搜索这个错误让我足够怀疑我正在使用的绑定违反了子元素只能有一个父元素的规则,无论是在视觉上还是逻辑上。我也认为我觉得有问题的属性是我尝试将按钮的内容绑定到图像的地方。
如果堆栈面板中只有一个按钮使用这些绑定,则可以正常工作。但是不止一个按钮没有。
我真的不明白为什么这会违反单亲规则,或者知道如何修复它。有人可以将我的绑定演变为有效的吗?
干杯,
Berryl
<Style x:Key="BoundImageButtonStyle" TargetType="{x:Type Button}" >
<Setter Property="Content">
<Setter.Value>
<Image Source="{Binding SmallImage}" />
</Setter.Value>
</Setter>
<Setter Property="Command" Value="{Binding Command}" />
<Setter Property="ToolTip" Value="{Binding ToolTipTitle}" />
</Style>
<StackPanel Orientation="Horizontal" Height="30" Grid.Row="1" HorizontalAlignment="Center">
<StackPanel.Resources >
<sys:Double x:Key="btnSize">24</sys:Double>
<Style x:Key="btnStyle" TargetType="Button" BasedOn="{StaticResource BoundImageButtonStyle}">
<Setter Property="Height" Value="{StaticResource btnSize}" />
<Setter Property="Width" Value="{StaticResource btnSize}" />
</Style>
</StackPanel.Resources>
<Button Style="{StaticResource btnStyle}" DataContext="{Binding AddItemControl}" />
<Button Style="{StaticResource btnStyle}" DataContext="{Binding EditItemControl}" />
<Button Style="{StaticResource btnStyle}" DataContext="{Binding DeleteItemControl}" />
</StackPanel>
public ButtonData AddItemControl
{
get
{
return _addItemControl ??
(_addItemControl = new ButtonData
{
ToolTipTitle = _crudTextConverter.AddNew(this),
SmallImage =
"pack://application:,,,/Smack.Core.Presentation.Wpf;component/Images/simplicio_add.png",
Command = AddItemCommand,
});
}
}
private ButtonData _addItemControl;
答案 0 :(得分:1)
这仅为应用样式的所有控件创建一个 Image
:
<Setter Property="Content">
<Setter.Value>
<Image Source="{Binding SmallImage}" />
</Setter.Value>
</Setter>
您可以将图像外部化并使其成为non-shared:
<!-- In some compiled Resources dictionary that is accessible from the style -->
<Image x:Key="image" x:Shared="false"
Source="{Binding SmallImage}" />
<Setter Property="Content" Value="{StaticResource image}"/>
或者您可以设置ContentTemplate
,所有按钮都具有相同的模板实例,但ui元素是从它独立创建的:
<Setter Property="Content" Value="{Binding}"/>
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<Image Source="{Binding SmallImage}" />
</DataTemplate>
</Setter.Value>
</Setter>