如何在样式中设置绑定? [英] How to set a binding inside a style?

查看:47
本文介绍了如何在样式中设置绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am fairly new to Xaml.
I am learning UWP(Universal Windows Platform) and I have more buttons and I want to bind their Background property to a property of a ViewModel that will change during some events.

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

I implemented the INotifyPropertyChanged and everything works ok (the color of the buttons change) when I bind the Background property in the Buttons' declaration in XAML:

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

StaticResource AppViewModel 是 App.xaml 中的一个资源:

StaticResource AppViewModel is a resource in App.xaml:

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

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

I don't know how ok is to declare a ViewModel for App.xaml, but it's a solution I found for having global variables (the variables are held inside the viewModel).

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

Now back to my question: As I don't want to bind the Background on every single button, I tried to add it on the style like this:

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

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

But now when the color variable is changing during running the app, the UI doesn't update anymore. It seems that binded properties in styles don't respond to changes of variables.

我做错了什么?感谢您的回答.

What am I doing wrong? Thank you for any answers.

推荐答案

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

After more searching I found a video from Jerry Nixon : http://blog.jerrynixon.com/2013/01/walkthrough-dynamically-skinning-your.html

看来是因为我们在uwp/winrt中没有DynamicResource,所以要搞个小把戏:我们重新导航到同一帧.所以在我们改变属性之后,我们必须做这样的事情:

It seems that because we don't have DynamicResource in uwp / winrt, we have to do a trick: We renavigate to the same frame. So after we change the property, we have to do something like this:

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

这就像使 Windows 窗体中的控件无效.它使 UI 重绘本身.我不确定这是否有副作用,我将不得不进一步挖掘.找到的话我会回来的.

It's like invalidating a control in Windows Forms. It's making the UI redraw itself. I'm not sure if this has side effects, I'll have to dig more. I'll come back if I find any.

这篇关于如何在样式中设置绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆