弹出绑定错误

时间:2014-04-02 21:33:48

标签: c# wpf

我的绑定无法找到viewmodel。如果它是正常的列表框,一切都很好。但是当列表框处于弹出状态时,我无法正常工作。

<UserControl.DataContext>
  <viewModel:MyViewModel/>
</UserControl.DataContext>

  <Popup Name="MyPopUp" UseLayoutRounding="True" AllowsTransparency="False" IsOpen="True" Placement="Right">                                    
    <ListBox DataContext="viewModel:MyViewModel" 
SelectedItem="{Binding Path=SelectedListItem, Mode=TwoWay}" 
              ItemsSource="{Binding ListBoxContents}">
    </ListBox>
    </Popup>

在MyViewModel中

public ObservableCollection<double> ListBoxContents { get; set; }
public string SelectedListItem {get;set;}

ListBoxContents = new ObservableCollection<double>() {6,5,4};

绑定错误

System.Windows.Data Error: 40 : BindingExpression path error: 'ListBoxContents' property not found on 'object' ''String' (HashCode=-734831200)'. BindingExpression:Path=ListBoxContents; DataItem='String' (HashCode=-734831200); target element is 'ListBox' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')

System.Windows.Data Error: 40 : BindingExpression path error: 'SelectedListItem' property not found on 'object' ''String' (HashCode=-734831200)'. BindingExpression:Path=SelectedListItem; DataItem='String' (HashCode=-734831200); target element is 'ListBox' (Name=''); target property is 'SelectedItem' (type 'Object')

我检查了拼写错误。我正在学习窥探,看看是否有帮助。

2 个答案:

答案 0 :(得分:2)

将您的代码更改为:

  <Popup Name="MyPopUp" UseLayoutRounding="True" AllowsTransparency="False" IsOpen="True" Placement="Right">
    <Popup.DataContext>
        <viewModel:MyViewModel/>
    </Popup.DataContext>    
    <ListBox SelectedItem="{Binding Path=SelectedListItem, Mode=TwoWay}" ItemsSource="{Binding ListBoxContents}" />
  </Popup>

答案 1 :(得分:0)

您在此处设置字符串("viewModel:MyViewModel")作为ListBox的DataContext:

<ListBox DataContext="viewModel:MyViewModel"  
         ....>

因此,你得到了绑定错误,字符串没有属性ListBoxContents也没有SelectedListItem。我真的怀疑你打算在那里做绑定,而不是直接设置值。

无论如何,修复可能更简单,只需从DataContext中删除ListBox设置,使其继承父级的DataContext:

<UserControl.DataContext>
  <viewModel:MyViewModel/>
</UserControl.DataContext>

<Popup Name="MyPopUp" UseLayoutRounding="True" AllowsTransparency="False" 
       IsOpen="True" Placement="Right">                                    
    <ListBox SelectedItem="{Binding Path=SelectedListItem, Mode=TwoWay}" 
             ItemsSource="{Binding ListBoxContents}">
    </ListBox>
</Popup>