开发者

WPF/MVVM: RichTexBox as datagrid cell editor, put formatting code into ViewModel?

开发者 https://www.devze.com 2023-01-09 12:38 出处:网络
I really wonder what I can put in the ViewModel. If its needed to be tested might some say... But when the properties like CaretPosition (to get the selected Text) are no dependency

I really wonder what I can put in the ViewModel.

If its needed to be tested might some say...

But when the properties like CaretPosition (to get the selected Text) are no dependency

properties, then better forget about the ViewModel.

At the moment I have this in the codebehind:

private void rtbContent_SelectionChanged(object sender, System.Windows.RoutedEventArgs e)
        {
            RichTextBox rtb = sender as RichTextBox;

            TextPointer tpForward = rtb.CaretPosition.GetNextContextPosition(LogicalDirection.Forward);
            TextPointer tpBackward = rtb.CaretPosition.GetNextContextPosition(LogicalDirection.Backward);

            if (tpForward != null && tpBackward != null)
            {
                DependencyObject nextObj = tpForward.GetAdjacentElement(LogicalDirection.Forward);
                DependencyObject prevObj = tpBackward.GetAdjacentElement(LogicalDirection.Backward);

                TextElement textElement = (TextElement)(nextObj ?? prevObj);

                if (textElement != null)
                {
                    tbBold.IsChecked = textElement.FontWeight == FontWeights.Bold;
                    tbItalic.IsChecked = textElement.FontStyle == FontStyles.Italic;
                    //...
                }
            }          
        }

This code is formatting selected Text, toggles the state of the togglebutton when the cursor is before a formatted char/has formatted chars, just like in word...

1.) Where does such code belong? Code-behind or ViewModel? Actually I know the answer because of technical restrictions of the RTBox it will stay in the code-behind.

2.) The logic to toggle the format buttons is done via

But that will not work as the BoldCommand can not execute a method which would format the selected Text, as th开发者_运维知识库e selected Text of the RTB can not be bound to the ViewModel...

How to cope with that ?

UPDATE:

ward bell said:

"I am open to some code in the code-behind; ...I draw the line at decision logic. I smell a rat when I see a conditional statement of any kind. That’s where bugs breed. Conditional logic is code we should be testing."

source: http://codebetter.com/blogs/wardbell/archive/2010/03/19/mvvm-josh-smith-s-way.aspx


Data goes in the Model, UI goes in the View, and that includes formatting text for display. Now, keep in mind the View can also include code-behind--it does not have to be strictly XAML.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号