【问题标题】:How to set a binding inside a style?如何在样式中设置绑定?
【发布时间】:2016-01-15 01:02:29
【问题描述】:

我对 Xaml 还很陌生。
我正在学习 UWP(通用 Windows 平台),我有更多按钮,我想将它们的 Background 属性绑定到 ViewModel 的属性,该属性将在某些事件期间发生变化。

当我在 XAML 的按钮声明中绑定 Background 属性时,我实现了 INotifyPropertyChanged 并且一切正常(按钮的颜色发生变化):

<Button Content="0" Grid.Column="0" Grid.Row="5"
                Background="{Binding ButtonColor, Source={StaticResource AppViewModel}}" Style="{StaticResource BasicButton}"/>

StaticResource AppViewModel 是 App.xaml 中的资源:

<Application.Resources>
    <viewModel:AppViewModel x:Key="AppViewModel" />
</Application.Resources>

我不知道如何为 App.xaml 声明 ViewModel,但这是我找到的具有全局变量的解决方案(变量保存在 viewModel 中)。

现在回到我的问题: 由于我不想在每个按钮上绑定背景,我尝试将它添加到这样的样式中:

<Style x:Key="BasicButton" TargetType="Button">
            <Setter Property="Background" Value="{Binding ButtonColor, Source={StaticResource AppViewModel}}" />
</Style>

但是现在当颜色变量在运行应用程序期间发生变化时,UI 不再更新。 样式中的绑定属性似乎不会响应变量的变化。

我做错了什么? 感谢您的任何回答。

【问题讨论】:

  • 您是否尝试将视图模型用作 DynamicResource?
  • DynamicResource 不存在于 uwp / windows store 应用程序 api 中
  • 它不起作用的原因是因为样式是作为staticResource添加的,所以即使它在幕后发生变化,它也会通知链接的按钮。
  • 什么是解决方案?
  • 不确定,但这可能会有所帮助 - c-sharpcorner.com/UploadFile/7078b8/…

标签: c# xaml mvvm windows-phone-8.1 uwp


【解决方案1】:

经过更多搜索,我找到了 Jerry Nixon 的视频:http://blog.jerrynixon.com/2013/01/walkthrough-dynamically-skinning-your.html

看来是因为我们在uwp/winrt中没有DynamicResource,所以不得不做个小技巧: 我们重新导航到同一帧。所以在我们改变属性之后,我们要做这样的事情:

var frame = Window.Current.Content as Frame;
frame.Navigate(frame.Content.GetType());
frame.GoBack();

这就像在 Windows 窗体中使控件无效。它使 UI 重绘本身。 我不确定这是否有副作用,我将不得不挖掘更多。找到了我会回来的。

【讨论】:

  • 我正在查看同一个博客 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-21
  • 2017-01-30
  • 1970-01-01
  • 2011-07-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多