Change WPF button background image programmatically

前端 未结 2 1413
野趣味
野趣味 2021-01-14 11:11

I\'m trying to create a

2条回答
  •  独厮守ぢ
    2021-01-14 11:41

    Sigh, in Windows Forms it was literally one line. In WPF it looks like it will be several hundred.

    That's because it was the ONLY thing you could place in a button in winforms. WPF is a true UI framework, not some random semi-deprecated dinosaur that only allows to do the default stuff (which by the way looks horrible).

    Option 1: Place the Image as Button's Content:

    If you just want to place an Image in the button, and nothing else, why not just do that?

            
    

    Then:

         
        
        
    
        
        
    

    Result:

    enter image description here

    Option 2 (not very elegant): Use the Tag Property:

    If, in addition to the Image, you want to put something else inside the Button, you can resort to a somewhat hacky approach of putting the ImageSource in the Button's Tag property.

            
    

    Then:

        
    

    Result:

    enter image description here

    Option 3: Use an Attached Property

    Same as option 2, but using a property declared elsewhere, for example:

     

    Option 4: Create a Custom Control:

    Create a class (.cs file with no XAML) derived from Button and add a DependencyProperty to hold the image, then set the template to that and use that value.

    Option 5: MVVM

    Create a ButtonViewModel, or actually use a DelegateCommand declared in the ViewModel to bind the Button's properties.

    Not an Option: Traverse the Visual Tree and change the Image.Source in code.

    That's not something you will want to do. It's not a good approach at all.

    I could go on forever, but I have to go to sleep. If you want me to elaborate on any of these approaches just let me know.

提交回复
热议问题