英文:
C# wpf mvvm programmatically change border color programmatically
问题
我是初学者 - 我有一个包含图像的边框,在xaml代码中最终可能有许多这样的边框/照片。
这个边框有一个属性Name="Border_N"(N = 独特的边框ID值),我想点击这个作为按钮的照片,然后边框会改变颜色。
我希望能够以编程方式做到这一点,但我真的不确定如何最好地进行。我相信这不可能很难,但我真的不确定从哪里开始。有人知道吗?
英文:
I'm a beginner - I have a Border with an image inside, there could ultimately be many of these border/photos in xaml code.
The border(s) have an attribute Name="Border_N" (N = a unique border id value) I'd like to click on this photo which is a button and have the border change colour.
I want to be able do this programmatically but, I'm really not sure how best to go about this. I'm sure this can't be difficult, but I'm really not sure where to start. Anyone know?
答案1
得分: 1
你不想以编程方式更改边框颜色。甚至在点击时也不想更改边框颜色。相反,你想要在你的视图模型中引入一些状态,表示"这张照片"被点击了(比如,bool ThisPhotoIsClicked { get; set; }
,希望你能找到一个更有意义的名称),然后根据该状态选择边框的颜色。
为此,你有一些选项:
-
你可以使用绑定和一个布尔到颜色的转换器将边框的颜色与状态绑定在一起(参见 https://stackoverflow.com/a/32526689/773113)
-
你可以为边框分配一个样式,其中包含触发器,以根据不同的状态实现不同的颜色(参见 https://stackoverflow.com/a/8534694/773113)
英文:
You do not want to change your border color programmatically. You do not even want to change your border color when something is clicked. What you want to do instead is to introduce some state in your viewmodel, which represents the fact that "this photo" is clicked, (say, bool ThisPhotoIsClicked { get; set; }
, hopefully you will find a more meaningful name,) and then you want to make your border select its color based on that state.
For this, you have a couple of options:
-
You can bind the color of the border to the state using a binding with a boolean-to-color converter (see https://stackoverflow.com/a/32526689/773113)
-
You can assign a style to your border which incorporates triggers to realize different colors based on different states (see https://stackoverflow.com/a/8534694/773113)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论