从ViewModel访问View中对象的属性

时间:2014-01-09 16:49:50

标签: wpf view properties viewmodel

我的视图中有一个TabControl,其中包含多个TabItems。我想从我的ViewModel更改IsSelected之一的TabItems属性。

以下是视图的xaml代码:

<TabControl Height="50" Margin="12,0,0,0">
                    <TabItem Name="tiCaptureSetup" >
                        <TabItem.Header>                            
                            <Button Name="btnCaptureSetup"
                                    Grid.Column="0"
                                    Width="90"
                                    Height="40"
                                    Margin="5"
                                    ToolTip="Capture Setup"
                                    Content="Capture Setup"
                                    Click="btnCaptureSetup_Click"
                                    IsEnabled="{Binding Path=CaptureSetupButtonStatus, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
                                    IsDefault="True"
                                    ></Button>
                        </TabItem.Header>
                    </TabItem>

以下是View

中的C#代码
private void btnCaptureSetup_Click(object sender, RoutedEventArgs e)
        {
            tiCaptureSetup.IsSelected = true;   //select Capture Setup TabItem

            MenuLSViewModel vm = (MenuLSViewModel)this.DataContext;

            if (vm != null)
            {
                vm.CaptureSetupCommand.Execute(null);
            }
        }

我想从ViewModel更改tiCaptureSetup.IsSelected

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

最简单的方法:在ViewModel中创建一个名为IsCaptureSetupSelected的属性,并将其绑定到IsSelected的{​​{1}}属性

视图模型:

tiCaptureSetup.

XAML:

private bool _IsCaptureSetupSelected;
public bool IsCaptureSetupSelected
{
    get { return _IsCaptureSetupSelected; }
    set
    {
            if (_IsCaptureSetupSelected != value)
            {
                    _IsCaptureSetupSelected = value;
                    RaisePropertyChanged();
            }
    }
}

请注意,我假设您正在使用ViewModel等MVVMLight ......