绑定按钮' WP7 中 ViewModel 属性的样式
我在音频记录视图中有一个播放按钮。
目前它被定义为:
<Button Width="72" Height="72" Style="{StaticResource RoundPlay}"
DataContext="{Binding ElementName=this, Path=DataContext}"
cmd:ButtonBaseExtensions.Command="{Binding PlayStopCommand}"
/>
当用户单击按钮时,项目 ViewModel 中的 PlayStopCommand 被执行。我希望每当声音播放时按钮的样式设置为“RoundStop”。
如何将按钮的样式绑定到 ViewModel 中的属性(我应该使用什么属性类型),以便可以通过代码控制按钮的外观?
我定义了 RoundStop 样式,我只需要一种将其应用到代码中的按钮的方法。
I have a play button in a AudioRecord View.
Currently it is declered as:
<Button Width="72" Height="72" Style="{StaticResource RoundPlay}"
DataContext="{Binding ElementName=this, Path=DataContext}"
cmd:ButtonBaseExtensions.Command="{Binding PlayStopCommand}"
/>
When a user clicks the button, a PlayStopCommand in items ViewModel gets executed. I want the button to get its' style set to "RoundStop" whenever the sound is playing.
How can I bind the buttons' Style to a property in my ViewModel (what property type should I use), so that the look of the button is controllable from code?
I have RoundStop style defined, I just need a way to apply it to a button from code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该在视图模型中定义播放状态(播放/停止),并使用转换器将 Button.Style 绑定到该属性。在转换器中,根据当前状态返回不同的样式(取自 App.Current.Resources)。
编辑:
以下是转换器的示例,应如下所示:
在此示例中,PlaybackState 是一个枚举:
然后您应该将状态属性添加到视图模型中(通知更改的部分取决于用于 MVVM 的框架):
在 XAML 中声明您的转换器:
最后将其绑定到按钮:
You should define the playing state in you viewmodel (Playing/Stopped), and bind Button.Style to that property using a converter. In your converter, return a different style (taken from App.Current.Resources) based on the current state.
Edit:
Here's an example of your converter should look like:
In this example, PlaybackState is an enum:
Then you should add the state property to your view model (The part where you notify the change depends on the framework you are using for MVVM):
Declare your converter in XAML:
And finally bind it to the button:
您可以使用 ToggleButton 并在选中/未选中的视觉状态中进行必要的视觉更改。
如果您必须按照问题所述的方式进行操作,那么您可以在资源中定义样式,然后在
this.Resources["YourStyleKey"];< 的代码隐藏中访问它/code> 您的问题是将其从视图获取到视图模型,因此我的第一个建议:)
You could use a
ToggleButton
and make the necessary visual changes in the visual states for checked/unchecked.If you must do it the way your question states, then you can define the Style in the resources and then access it in the code-behind from
this.Resources["YourStyleKey"];
Your problem will be getting it from the view to the view model, hence my first suggestion :)