MVVM Treeview selected item

你离开我真会死。 提交于 2019-12-22 18:45:10

问题


I hope someone is willing to help me out here. I`m pretty new to MVVM, an after reading manny post and examples i still cant figure this out.

i have EF database filled with items and calculations that belong to each Item. i`m showing the items and calculations using a treeview and HierarchicalDataTemplate. when i click on a treeview item, i want to bind the text of a label to be set at

public string totaalPrijs

but i just cant figure out how to do that!

this is how my CalculationViewModel looks

namespace Treeview_test1.ViewModel
{
public class CalculationViewModel : ViewModelBase
{
    public CalculationViewModel(TableItemChildren child)
    {
        this.Child = child;
        IsChecked = false;
    }

    public TableItemChildren Child { get; protected set; }

    public string totaalPrijs
    {
        get { return Child.dbTotaalPrijs; }
        set
        {
            if (Child.dbTotaalPrijs != value)
            {
                Child.dbTotaalPrijs = value;
                RaisePropertyChanged("totaalPrijs");
            }
        }
    }

    private bool _isChecked;
    public bool IsChecked
    {
        get { return _isChecked; }
        set
        {
            if (_isChecked != value)
            {
                _isChecked = value;
                RaisePropertyChanged("IsChecked");
            }
        }
    }

}

and here is my ItemViewModel

namespace Treeview_test1.ViewModel
{
public class ItemViewModel : ViewModelBase
{
    public ItemViewModel()
    {
        calcVMColl = new ObservableCollection<CalculationViewModel>();
        foreach (TableItemChildren calc in Service.getItemCalculations("1"))
        {
            calcVMColl.Add(new CalculationViewModel(calc));
        }
    }

    // Switch between real and mock data
    private IGetCalculations _service;
    public IGetCalculations Service
    {
        get
        {
            if (_service == null)
            {
                if (IsInDesignMode)
                    _service = new MockCalculations();
                else
                    _service = new GetCalculations();
            }
            return _service;
        }
        set
        {
            _service = value;
        }
    }

    private ObservableCollection<CalculationViewModel> _calcVMColl;
    public ObservableCollection<CalculationViewModel> calcVMColl
    {
        get { return _calcVMColl; }
        set
        {
            if (calcVMColl != value)
            {
                _calcVMColl = value;
                RaisePropertyChanged("calcVMColl");
            }
        }
    }
}

and XAML

<Window x:Class="Treeview_test1.MainWindow" xmlns="http://schemas.microsoft.com/   winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" xmlns:ViewModel="clr-namespace:Treeview_test1.ViewModel">
<Window.DataContext>
    <ViewModel:ItemViewModel />
</Window.DataContext>
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="204" />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <TreeView x:Name="tree" Width="195" HorizontalAlignment="Left" ItemsSource="{Binding calcVMColl}" Background="LightGray" Grid.Column="0" RenderTransformOrigin="1.016,0.509">
        <TreeView.ItemContainerStyle>
            <Style TargetType="{x:Type TreeViewItem}">
                <Setter Property="IsSelected" Value="{Binding IsChecked, Mode=TwoWay}" />
                <Style.Triggers>
                    <Trigger Property="IsSelected" Value="True">
                        <Setter Property="FontSize" Value="10" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </TreeView.ItemContainerStyle>
        <TreeView.Resources>
            <DataTemplate DataType="{x:Type ViewModel:CalculationViewModel}">
                <Label Content="{Binding totaalPrijs}" />
            </DataTemplate>
        </TreeView.Resources>
    </TreeView>
    <Label Grid.Column="1" HorizontalAlignment="Left" Margin="39,39,0,0" VerticalAlignment="Top" Content="{Binding....?}" Foreground="Black" FontFamily="segeo ui" FontSize="20" />
</Grid>

So in short: How do i bind the text of my label to the current selected treeview item?

thanks in advance

Addy


回答1:


Binding the SelectedItem of a TreeView to a Label (or TextBlock) is fairly simple:

<TreeView Name="myTreeview"/>
<TextBlock Text="{Binding SelectedItem, ElementName=myTreeview, Mode=OneWay}"/>

However this won't actually display what you want, since the SelectedItem of the TreeView is typically an Object and you need a string to display in the TextBlock.

One way to handle this is to use a Converter on the binding. You can implement IValueConverter and have it return the needed string from the SelectedItem.

   class GetTextFromItemConverter : IValueConverter
   {
      object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
      {
         TreeViewItem itm = (TreeViewItem)value;
         string myString = null;
         //Retrieve whatever portion of the TreeViewItem you want to put in myString.
         return myString;
      }

      object IValueConverter.ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
      {
         throw new NotImplementedException();
      }
   }

Then the binding on your TextBlock will look like this:

<TextBlock Text="{Binding SelectedItem, Converter={StaticResource GetTextFromItemConverter}, ElementName=myTreeview, Mode=OneWay}"/>


来源:https://stackoverflow.com/questions/17046221/mvvm-treeview-selected-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!