开发者

WPF Tree Binding Problem using Methods

I have bound a WPF TreeView to an ObservableCollection. When a Connection node gets 开发者_如何转开发expanded in the UI, I want Connection.GetDatabases() to be called, which returns an collection of Databases.

I'm using HierarchicalDataTemplate:

<HierarchicalDataTemplate DataType="{x:Type dbcore:Connection}" ItemsSource="<WHAT GOES HERE?>">
            <StackPanel Orientation="Horizontal">
                <Image Source="{StaticResource DataServerIcon}" Margin="5,2" />
                <TextBlock Text="{Binding Converter={StaticResource connToStringConverter}}" />
            </StackPanel>
</HierarchicalDataTemplate>

But because I want to use a method instead of a property, I'm not sure what to use in the ItemsSource property.


Since you want to get the values when the item is expanded you cannot do it in XAML at design time. You can do it when you your item is expanded in code behind:

<TreeView TreeViewItem.Expanded="OnExpanded" ... >


private void OnExpanded(object sender, RoutedEventArgs e)
{
      TreeViewItem tvi = e.OriginalSource as TreeViewItem;
      if (tvi != null)
      {
        tvi.Focus(); // to ensure the expanded item is selected
        tvi.ItemsSource = ((Connection)myTreeView.SelectedItem).GetDatabases();
      }
}


You can make an IValueConverter which takes your object and calls the method.

However, it would be much simpler, and probably a little bit faster, to add a proeprty to the original object that calls the method.
You may want to add [Obsolete("Please call MyMethod() instead.", true)] to prevent the property form being used in code. (This will not interfere with data-binding)


Why not simply use a property which will return the data via whatever method/service you want? You can't natively bind to a method; so either access your method within the properties getter or make use of an IValueConverter and parameter which could contain the method to call.

public ObservableColection<Database> Databases
{
     get
     {
        return GetDatabases();
     }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜