简体   繁体   中英

WPF/C#/MVVM: Need Some Help Implementing Custom View Options for User Control

The project I am currently working on is a text editor type app. I am wondering how I can handle custom view options. eg. font family, size, bold, colors for my TextBox . My Editor Tab is a EditorTabViewModel within the View is a custom user control MarkdownEditor . Its basically a text box with some buttons for bold/italic etc. I am wondering how can I somehow set options for the custom usercontrol/editor from like a OptionsView of my app?

the way I am rendering the editor is

<Window.Resources>
    <DataTemplate DataType="{x:Type vm:EditorTabViewModel}">
        <me:MarkdownEditor />
    </DataTemplate>
</Window.Resources>

MarkdownEditor is a user control that exposes public display properties for setting fonts, colors etc.

UPDATE : also since there can be many MarkdownEditor s in the app, I want the options to be global

There is nothing keeping you from having View constructs in your ViewModel... especially if you consider the ViewModel to be a model of the View (as opposed to a view of the model). Not all purists think this is a good idea. Most pragmatists, however, do.

Having properties like FontWeight, FontColor, FontSize, etc in your EditorTabViewModel would work for you here, and you can then bind them in the properties of the MarkdownEditor . It would allow for you to dynamically change the UI properties of the text via the ViewModel.

If you are a purist, and you don't like having the ViewModel know about WPF specific View constructs, you could create your own text formatting class, called something like TextFormatting . TextFormatting can include your own representation of the information you want to communicate (bold, italics, color, font size, etc). You can then bind that TextFormatting object to the MarkdownEditor using an attached property/behavior. The attached property/behavior would be responsible for mapping the formatting representation to the WPF representation.

Doing it the second way is very useful if you have different Views (WinForms/WPF) that might use the same ViewModel, since it remains view engine agnostic. It also adds a layer of complexity that the first option does not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM