1

我很困扰。我有一个 xml 文件,我绑定到该文件以进行某些显示。我的 xml 的一部分如下所示:

<Section Name="Water Efficiency">
  <Prerequisite Title="Prerequisite 1" Description="Water Use Reduction—20% Reduction " />
  <Credit CanCheckFromModel="False" CheckFromModel="False" Title="Credit 1" Description="Water Efficient Landscaping" IsGoal="Yes" PossiblePoints="2 to 4">
    <Option Description="Reduce by 50%" PossiblePoints="2" />
    <Option Description="No Potable Water Use or Irrigation" PossiblePoints="4" />
  </Credit>
  <Credit CanCheckFromModel="False" CheckFromModel="False" Title="Credit 2" Description="Innovative Wastewater Technologies" IsGoal="Yes" PossiblePoints="2" />
  <Credit CanCheckFromModel="True" CheckFromModel="True" Title="Credit 3" Description="Water Use Reduction " IsGoal="Yes" PossiblePoints="2 to 4">
    <Option Description="Reduce by 30%" PossiblePoints="2" />
    <Option Description="Reduce by 35%" PossiblePoints="3" />
    <Option Description="Reduce by 40%" PossiblePoints="4" />
  </Credit>
</Section>

基本上我有一个“选项”的组合框,我可以很好地填充它,如果没有选项,它是空白的。现在,如果没有选项,我希望它禁用。我为此创建了一个转换器,转换代码如下:

//convert to an xmlnodelist
XmlNodeList s = value as XmlNodeList;

System.Diagnostics.Debugger.Break();

//make sure the conversion worked
if (s != null)
{
  //see if there are any nodes in the list
  if (s.Count != 0)
  {
    //has nodes, check to see if any of them are of type 'Option'
    bool HasOptions = false;
    foreach (XmlNode n in s)
    {
      if (n.Name == "Option")
      {
        //found one with an option, exit loop
        HasOptions = true;
        break;
      }
    }

    //check if we found any options and return accordingly
    return HasOptions;
  }
}

//conversion failed or count was 0, false by default
return false;

我的组合框的 XAML 标记是:

<ComboBox Width="200" DataContext="{Binding}"  ItemsSource="{Binding XPath=./*}" IsEnabled="{Binding XPath=./*, Converter={StaticResource ConvOptions}}" >
  <ComboBox.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="{Binding XPath=@Description}" />
    </DataTemplate>
  </ComboBox.ItemTemplate>
</ComboBox>

对我来说真正令人困惑的部分是这反过来起作用。具有选项子项的条目被禁用,而没有的条目被启用。如果我只是切换返回值,那么我会启用所有功能,所以它就像它永远不会触及那些没有选项的东西。我尝试在转换器中放置一个断点,但它向我显示的所有值都是一个空字符串。

有人能告诉我这里发生了什么吗?

4

1 回答 1

1

乍一看,通过HasOptions一起删除来更新您的转换器,然后在找到时返回 true:

if (n.Name == "Option")
{
    //found one with an option, exit loop
    return true;
}

在转换器中,HasOptions在语句内部if (s.Count != 0)声明,但在 if 语句范围之外用作返回值。我不完全确定这会纠正转换器,但试一试。

附带说明:当在转换器中引发异常时,WPF 只会吞下它;检查您的输出窗口,由于转换器失败,您可能会看到绑定错误。

于 2012-09-18T18:51:50.547 回答