I have a UserControl with some custom dependency properties bound to a clr property in the ViewModel. The ViewModel has applica开发者_JS百科tion logic where I deal with the TextPointer/TextRange classes with a FlowDocument.
Should I put that stuff into the code-behind of the UserControl or in the ViewModel?
ranges.Clear();
TextRange range = new TextRange(boundXamlDocument.ContentStart, boundXamlDocument.ContentEnd);
foreach (var block in boundXamlDocument.Blocks)
{
if (block is Paragraph)
{
Paragraph p = block as Paragraph;
//if paragraph has Strikethrough, then do not loop its inlines.
if (p.TextDecorations.Contains(TextDecorations.Strikethrough[0]))
{
TextRange tr = new TextRange(p.ContentStart, p.ContentEnd);
ranges.Add(tr);
}
else
{
foreach (var run in p.Inlines)
{
if (run.TextDecorations.Contains(TextDecorations.Strikethrough[0]))
{
TextRange tr = new TextRange(run.ContentStart, run.ContentEnd);
ranges.Add(tr);
}
}
}
}
}
I only bother to design custom/user controls when I have a concept that won't fit well into any of the usual controls (rare to never), or I have custom control behavior that I want to reuse (more common).
The more abstract your control can be, the more reusable it will be. Although, making it so abstract that no one would get any benefit from it would be doing too much :)
If you have application logic, it is best to define it in the view model (or model) when at all possible. When that logic changes, it won't break other users of your control.
If a feature of the control isn't specific to the exact presentation/user input style, and is specific to that instance of the control, you should probably put it in the view model.
Edit:
From your comments, it seems that the code you are trying to write depends on UI elements (TextBlock text decorators). This means it must and should go in the view.
精彩评论