Skip to content

Commit

Permalink
Behave better if s:View.Model used on a bad container
Browse files Browse the repository at this point in the history
Fixes #6
  • Loading branch information
canton7 committed Jun 2, 2015
1 parent 9719289 commit 5e412af
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
13 changes: 8 additions & 5 deletions Stylet/Xaml/View.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;
using System.Reflection;

namespace Stylet.Xaml
{
Expand All @@ -22,8 +23,6 @@ public class View : DependencyObject
/// </summary>
public static readonly object InitialActionTarget = new object();

private static readonly ContentPropertyAttribute defaultContentProperty = new ContentPropertyAttribute("Content");

/// <summary>
/// Get the ActionTarget associated with the given object
/// </summary>
Expand Down Expand Up @@ -115,9 +114,13 @@ public static void SetModel(DependencyObject obj, object value)
public static void SetContentProperty(DependencyObject targetLocation, UIElement view)
{
var type = targetLocation.GetType();
var contentProperty = Attribute.GetCustomAttributes(type, true).OfType<ContentPropertyAttribute>().FirstOrDefault() ?? defaultContentProperty;

type.GetProperty(contentProperty.Name).SetValue(targetLocation, view, null);
var attribute = type.GetCustomAttribute<ContentPropertyAttribute>();
// No attribute? Try a property called 'Content'...
string propertyName = attribute != null ? attribute.Name : "Content";
var property = type.GetProperty(propertyName);
if (property == null)
throw new InvalidOperationException(String.Format("Unable to find a Content property on type {0}. Make sure you're using 's:View.Model' on a suitable container, e.g. a ContentControl", type.Name));
property.SetValue(targetLocation, view);
}

// Stop someone from instantiating us
Expand Down
9 changes: 9 additions & 0 deletions StyletUnitTests/ViewTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,15 @@ public void SetsContentControlContentProperty()
Assert.AreEqual(obj.Content, view);
}

[Test]
public void SetContentControlThrowsIfNoContentProperty()
{
var obj = new DependencyObject();
var view = new UIElement();

Assert.Throws<InvalidOperationException>(() => View.SetContentProperty(obj, view));
}

[Test]
public void SettingModelThrowsExceptionIfViewManagerNotSet()
{
Expand Down

0 comments on commit 5e412af

Please sign in to comment.