如何将数据从 View 绑定到 ViewModel?

How to bind data from View to ViewModel?

我对 mvvm 知之甚少,但到目前为止我是这样写代码的:

<Image x:Name ="new_tooltip" Grid.Row="84" Grid.Column="57" Grid.ColumnSpan="78"  Grid.RowSpan="15"  Source="/MS_Show_Assets/MainMenuAssets/TT-Startscreen-MainMenu-New-DE.png" Visibility = "{Binding IsMouseOver, ElementName=New, Converter={StaticResource BooleanToVisibilityConverter}}">
            <Image.Style>
                <Style TargetType="{x:Type Image}">
                    <Setter Property="Visibility" Value="{Binding Path=IsNewTooltipVisible, Mode=OneWayToSource}" />
                </Style>
            </Image.Style>
        </Image>

和视图模型:

public class ViewMainMenuViewModel : BindableBase
    {
        public string IsNewTooltipVisible { get; set; }

        public ViewMainMenuViewModel()
        {

        }
    }

所以基本上,如果鼠标悬停在某个按钮上,我希望视图中的某些图像变得可见。然后,一旦该图像可见,我想将 "Visible" 发送到 ViewModel class 中的 属性。 class 我还缺少什么?

您不需要 属性 在 VM 中执行此操作。您可以使用 Trigger on View 本身在按钮鼠标悬停时 show/hide 图像,如下所示。这里的 ElementName 是你想要捕获其鼠标悬停的按钮的名称。

<Image x:Name ="new_tooltip" Grid.Row="84" Grid.Column="57" Grid.ColumnSpan="78"  Grid.RowSpan="15"  Source="/MS_Show_Assets/MainMenuAssets/TT-Startscreen-MainMenu-New-DE.png" Visibility = "{Binding IsMouseOver, ElementName=New, Converter={StaticResource BooleanToVisibilityConverter}}">
            <Image.Style>
                <Style TargetType="{x:Type Image}">
                    <Setter Property="Visibility" Value="Collapsed"></Setter>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding IsMouseOver, ElementName=myButton}" Value="true">
                            <Setter Property="Visibility" Value="Visible"></Setter>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Image.Style>
        </Image>