【问题标题】:How to bind data from View to ViewModel?如何将数据从 View 绑定到 ViewModel?
【发布时间】:2016-03-25 11:54:52
【问题描述】:

我对 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>

和 ViewModel:

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

        public ViewMainMenuViewModel()
        {

        }
    }

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

【问题讨论】:

  • 不要将“Visible”发送到视图模型,如果你这样做了,那么你就违反了 MVVM 的基本规则之一(视图和视图模型之间的分离)。
  • 是的,我知道...我应该将它作为布尔值或字符串发送,并且我知道我应该使用可见性到布尔值转换器...。
  • 尝试使用OneWayToSource绑定IsMouseOver?我认为这在以前的 .NET 版本中是不可能的,也许现在不会了。

标签: wpf xaml mvvm prism


【解决方案1】:

您不需要 VM 中的属性来执行此操作。您可以使用 Trigger on View 本身在按钮鼠标悬停时显示/隐藏图像,如下所示。这里 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>

【讨论】:

  • 感谢您的回答。我想将它发送到 ViewModel 中的属性的原因是因为我有另一个视图(XAML),其中还需要在第一个视图中的鼠标悬停按钮上进行更改。所以这就是为什么我想将它存储在属性中,然后将它进一步传递给其他视图模型或其他东西......
猜你喜欢
  • 1970-01-01
  • 2015-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多