【问题标题】:Changing selected element in WPF更改 WPF 中的选定元素
【发布时间】:2012-04-26 04:59:25
【问题描述】:

我对 WPF 完全陌生。

我正在用 MVVM 模式制作一个简单的应用程序。

我有一个视图模型,其中引用了一个模型。该模型包含一些我想放入组合框中的网络元素。

这是视图模型的相关部分:

public class MainWindowVM : ViewModelBase
{
    private Model _model = null;

    public Model Model
    {
        get
        {
            return _model;
        }
    }

    #region ActiveElement

    private NetElement _activeElement = null;

    public NetElement ActiveElement
    {
        get
        {
            return _activeElement;
        }
        set
        {
            if (_activeElement != value)
            {
                _activeElement = value;
                RaisePropertyChanged("ActiveElement");
                if (ActiveElementChanged != null)
                    ActiveElementChanged(this, EventArgs.Empty);
            }
        }
    }
}

我希望能够在组合框中选择一个 NetElement 并将 ActiveElement 设置为它。

这是我当前 XAML 的相关部分:

<ItemsControl Background="White" IsTabStop="True" ItemsSource="{Binding Path=Model.RootNet.Elements}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Margin="2,6">
            <Hyperlink Command="{Binding Path=I'm not able to figure out what to write here}">
              <TextBlock Text="{Binding Path=Name}" />
            </Hyperlink>
          </TextBlock>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

这不是一个组合框,而是一个文本块列表,但你可以看到它的去向。

如何从视图中设置 ActiveElement?

【问题讨论】:

    标签: c# wpf binding mvvm selection


    【解决方案1】:

    为 ComboBox 的 SelectedItem 属性创建与您的 ActiveElement 属性的绑定:

     <ComboBox SelectedItem="{Binding Path=ActiveElement}" ... />
    

    然后将视图的 DataContext 属性设置为您的视图模型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-14
      • 1970-01-01
      • 1970-01-01
      • 2015-06-05
      • 1970-01-01
      相关资源
      最近更新 更多