小编Ber*_*tAR的帖子

无法找到参考“RelativeSource FindAncestor”进行绑定的源

我正在使用复合集合:

  • 内容为“选择供应商”的组合框项
  • 绑定到 Vendor 对象的 Observable 集合的 Collection 容器

所需的功能:用户必须从组合框中选择供应商。选择“选择供应商”会将视图模型中的 Vendor 属性设置为 null。

我收到绑定错误。任何想法如何解决这一问题?

调试时出错

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=HorizontalContentAlignment; DataItem=null; target element is 'ComboBoxItem' (Name=''); target property is 'HorizontalContentAlignment' (type 'HorizontalAlignment')
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=VerticalContentAlignment; DataItem=null; target element is 'ComboBoxItem' (Name=''); target property is 'VerticalContentAlignment' (type 'VerticalAlignment')
Run Code Online (Sandbox Code Playgroud)

XAML

<ComboBox Name='cmbVendor'
            SelectedItem='{Binding Vendor, Converter={StaticResource ComboboxConverter}, Mode=TwoWay}'
            IsSynchronizedWithCurrentItem='True'> …
Run Code Online (Sandbox Code Playgroud)

data-binding wpf xaml

7
推荐指数
3
解决办法
1万
查看次数

使用格式和缩进将 XElement 添加到 XML 文件

XML

源 XML

<!-- The comment -->
<Root xmlns="http://www.namespace.com">
    <FirstElement>
    </FirstElement>

    <SecondElement>
    </SecondElement>
</Root>
Run Code Online (Sandbox Code Playgroud)

所需的 XML

<!-- The comment -->
<Root xmlns="http://www.namespace.com">
    <FirstElement>
    </FirstElement>

    <SecondElement>
    </SecondElement>

    <ThirdElement>
        <FourthElement>thevalue</FourthElement>
    </ThirdElement>
</Root>
Run Code Online (Sandbox Code Playgroud)

现在我的输出 XML 是

<!-- The comment -->
<Root xmlns="http://www.namespace.com">
    <FirstElement>
    </FirstElement>

    <SecondElement>
    </SecondElement><ThirdElement><FourthElement>thevalue</FourthElement></ThirdElement>
</Root>
Run Code Online (Sandbox Code Playgroud)

请注意,我需要加载 XML,LoadOptions.PreserveWhitespace因为我需要保留所有空格(客户需要)。所需的输出是在“根”的最后一个子元素之后放置 2 个换行符,并添加适当的缩进

<ThirdElement>
    <FourthElement>thevalue</FourthElement>
</ThirdElement>
Run Code Online (Sandbox Code Playgroud)

任何想法如何实现这一点?

代码

var xDoc = XDocument.Load(sourceXml, LoadOptions.PreserveWhitespace); //need to preserve all whitespaces
var mgr = new XmlNamespaceManager(new NameTable());
var ns = xDoc.Root.GetDefaultNamespace();
mgr.AddNamespace("ns", ns.NamespaceName);

if (xDoc.Root.HasElements)
{ …
Run Code Online (Sandbox Code Playgroud)

c# xml xelement linq-to-xml

4
推荐指数
1
解决办法
942
查看次数

标签 统计

c# ×1

data-binding ×1

linq-to-xml ×1

wpf ×1

xaml ×1

xelement ×1

xml ×1