Fix Resharper warnings, and downgrade unnecessary ones to Hint

This commit is contained in:
Antony Male 2015-01-12 10:24:26 +00:00
parent fd69a61ed5
commit 0b8c22fc08
40 changed files with 98 additions and 103 deletions

13
Stylet.sln.DotSettings Normal file
View File

@ -0,0 +1,13 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=CheckNamespace/@EntryIndexedValue">HINT</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=ConvertIfStatementToConditionalTernaryExpression/@EntryIndexedValue">HINT</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=ExplicitCallerInfoArgument/@EntryIndexedValue">HINT</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=FieldCanBeMadeReadOnly_002ELocal/@EntryIndexedValue">WARNING</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=LocalVariableHidesMember/@EntryIndexedValue">HINT</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=ParameterHidesMember/@EntryIndexedValue">HINT</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=RedundantAnonymousTypePropertyName/@EntryIndexedValue">HINT</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=RedundantAttributeUsageProperty/@EntryIndexedValue">HINT</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=RedundantUsingDirective/@EntryIndexedValue">HINT</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=UI/@EntryIndexedValue">UI</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=PrivateInstanceFields/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="aaBb"&gt;&lt;ExtraRule Prefix="_" Suffix="" Style="aaBb" /&gt;&lt;/Policy&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=PrivateStaticFields/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="aaBb"&gt;&lt;ExtraRule Prefix="_" Suffix="" Style="aaBb" /&gt;&lt;/Policy&gt;</s:String></wpf:ResourceDictionary>

View File

@ -29,7 +29,7 @@ namespace Stylet
/// Interface encapsulating IReadOnlyList and INotifyCollectionChanged
/// </summary>
/// <typeparam name="T">The type of elements in the collection</typeparam>
public interface IReadOnlyObservableCollection<T> : IReadOnlyList<T>, INotifyCollectionChanged, INotifyCollectionChanging
public interface IReadOnlyObservableCollection<out T> : IReadOnlyList<T>, INotifyCollectionChanged, INotifyCollectionChanging
{ }
/// <summary>
@ -112,7 +112,7 @@ namespace Stylet
var previousNotificationSetting = this.isNotifying;
this.isNotifying = false;
var index = Count;
var index = this.Count;
foreach (var item in items)
{
base.InsertItem(index, item);
@ -140,7 +140,7 @@ namespace Stylet
this.isNotifying = false;
foreach (var item in items)
{
var index = IndexOf(item);
var index = this.IndexOf(item);
if (index >= 0)
base.RemoveItem(index);
}

View File

@ -34,7 +34,7 @@ namespace Stylet
/// <summary>
/// Initialises a new instance of the <see cref="BootstrapperBase{TRootViewModel}"/> class
/// </summary>
public BootstrapperBase()
protected BootstrapperBase()
{
this.Assemblies = new List<Assembly>() { typeof(BootstrapperBase<>).Assembly, this.GetType().Assembly };
}

View File

@ -17,7 +17,7 @@ namespace Stylet
/// Implement this to handle a particular message type
/// </summary>
/// <typeparam name="TMessageType">Message type to handle. Can be a base class of the messsage type(s) to handle</typeparam>
public interface IHandle<TMessageType> : IHandle
public interface IHandle<in TMessageType> : IHandle
{
/// <summary>
/// Called whenever a message of type TMessageType is posted
@ -137,7 +137,7 @@ namespace Stylet
}
if (channels.Length == 0)
channels = new[] { EventAggregator.DefaultChannel };
channels = new[] { DefaultChannel };
this.SubscribeToChannels(channels);
}
@ -167,7 +167,7 @@ namespace Stylet
return false;
if (channels.Length == 0)
channels = new[] { EventAggregator.DefaultChannel };
channels = new[] { DefaultChannel };
// We're not subscribed to any of the channels
if (!channels.All(x => this.channels.Contains(x)))

View File

@ -2,7 +2,6 @@
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
namespace Stylet
{

View File

@ -17,8 +17,9 @@ namespace Stylet
public static string NameForProperty<TDelegate>(this Expression<TDelegate> propertyExpression)
{
Expression body;
if (propertyExpression.Body is UnaryExpression)
body = ((UnaryExpression)propertyExpression.Body).Operand;
var expression = propertyExpression.Body as UnaryExpression;
if (expression != null)
body = expression.Operand;
else
body = propertyExpression.Body;

View File

@ -1,6 +1,5 @@
using System;
using System.Windows;
using System.Windows.Threading;
namespace Stylet
{

View File

@ -46,6 +46,8 @@ namespace Stylet
/// Thing which owns one or more children, and can manage their lifecycles accordingly
/// </summary>
/// <typeparam name="T">Type of child being conducted</typeparam>
// ReSharper disable once TypeParameterCanBeVariant
// Not sure whether this might change in future...
public interface IConductor<T>
{
/// <summary>

View File

@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Threading;
namespace Stylet

View File

@ -1,9 +1,5 @@
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stylet
{
@ -15,6 +11,6 @@ namespace Stylet
/// <summary>
/// Occurs when the collection will change
/// </summary>
event NotifyCollectionChangedEventHandler CollectionChanged;
event NotifyCollectionChangedEventHandler CollectionChanging;
}
}

View File

@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
namespace Stylet
@ -15,6 +14,7 @@ namespace Stylet
/// and request a new IModelValidator{MyViewModelType} in your ViewModel's constructor.
/// </remarks>
/// <typeparam name="T">Type of model being validated</typeparam>
// ReSharper disable once UnusedTypeParameter
public interface IModelValidator<in T> : IModelValidator
{
}

View File

@ -4,14 +4,16 @@
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:s="clr-namespace:Stylet.Xaml"
xmlns:stylet="clr-namespace:Stylet"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance stylet:MessageBoxViewModel}"
ResizeMode="NoResize"
SizeToContent="WidthAndHeight"
FlowDirection="{Binding FlowDirection}"
WindowStartupLocation="CenterScreen"
ShowInTaskbar="False"
MinWidth="160" MaxWidth="485"
x:Name="rootObject">
x:Name="RootObject">
<Grid Margin="0,0,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="6"/> <!-- Padding -->
@ -31,7 +33,7 @@
<TextBlock Grid.Row="0" Grid.Column="2" Text="{Binding Text}" Margin="8,30,15,30" TextWrapping="Wrap" TextAlignment="{Binding TextAlignment}"/>
<Grid Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="3" Background="{DynamicResource {x:Static SystemColors.ControlBrushKey}}">
<ItemsControl Grid.Row="1" ItemsSource="{Binding ButtonList}"
<ItemsControl ItemsSource="{Binding ButtonList}"
HorizontalAlignment="Right" VerticalAlignment="Center" Margin="43,0,0,0">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
@ -45,13 +47,13 @@
<Button.IsDefault>
<MultiBinding Converter="{x:Static s:EqualityConverter.Instance}">
<Binding/>
<Binding Path="DataContext.DefaultButton" ElementName="rootObject"/>
<Binding Path="DataContext.DefaultButton" ElementName="RootObject"/>
</MultiBinding>
</Button.IsDefault>
<Button.IsCancel>
<MultiBinding Converter="{x:Static s:EqualityConverter.Instance}">
<Binding/>
<Binding Path="DataContext.CancelButton" ElementName="rootObject"/>
<Binding Path="DataContext.CancelButton" ElementName="RootObject"/>
</MultiBinding>
</Button.IsCancel>
</Button>

View File

@ -87,7 +87,7 @@ namespace Stylet
if (!EqualityComparer<T>.Default.Equals(field, value))
{
field = value;
this.NotifyOfPropertyChange(propertyName);
this.NotifyOfPropertyChange(propertyName: propertyName);
}
}
}

View File

@ -48,8 +48,8 @@ namespace Stylet
{
internal class StrongPropertyChangedBinding : IEventBinding
{
private WeakReference<INotifyPropertyChanged> inpc;
private PropertyChangedEventHandler handler;
private readonly WeakReference<INotifyPropertyChanged> inpc;
private readonly PropertyChangedEventHandler handler;
public StrongPropertyChangedBinding(INotifyPropertyChanged inpc, PropertyChangedEventHandler handler)
{
@ -68,9 +68,9 @@ namespace Stylet
internal class WeakPropertyChangedHandler<TSource, TProperty> : IEventBinding where TSource : class, INotifyPropertyChanged
{
private readonly WeakReference<TSource> source;
private EventHandler<PropertyChangedExtendedEventArgs<TProperty>> handler;
private string propertyName;
private Func<TSource, TProperty> valueSelector;
private readonly EventHandler<PropertyChangedExtendedEventArgs<TProperty>> handler;
private readonly string propertyName;
private readonly Func<TSource, TProperty> valueSelector;
public WeakPropertyChangedHandler(TSource source, Expression<Func<TSource, TProperty>> selector, EventHandler<PropertyChangedExtendedEventArgs<TProperty>> handler)
{
@ -104,7 +104,7 @@ namespace Stylet
internal class WeakPropertyChangedBinding : IEventBinding
{
private WeakReference<IEventBinding> wrappedBinding;
private readonly WeakReference<IEventBinding> wrappedBinding;
public WeakPropertyChangedBinding(IEventBinding wrappedBinding)
{

View File

@ -134,7 +134,7 @@ namespace Stylet
#region IClose
private bool isClosed = false;
private bool isClosed;
/// <summary>
/// Called whenever this Screen is closed

View File

@ -76,7 +76,7 @@ namespace Stylet
public static void CloseWith(this IClose child, IClose parent)
{
// Using TryCloseAndDispose ensures that Dispose is called if necessary
WeakEventManager<IClose, CloseEventArgs>.AddHandler(parent, "Closed", (o, e) => ScreenExtensions.TryCloseAndDispose(child));
WeakEventManager<IClose, CloseEventArgs>.AddHandler(parent, "Closed", (o, e) => TryCloseAndDispose(child));
}
/// <summary>

View File

@ -13,7 +13,7 @@ namespace StyletIoC.Internal.Builders
public string Key { get; protected set; }
public bool IsWeak { get; protected set; }
public BuilderBindingBase(Type serviceType)
protected BuilderBindingBase(Type serviceType)
{
this.ServiceType = serviceType;

View File

@ -1,9 +1,5 @@
using StyletIoC.Internal.Creators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System;
using StyletIoC.Internal.Creators;
namespace StyletIoC.Internal.Builders
{

View File

@ -8,7 +8,7 @@ namespace StyletIoC.Internal.Builders
{
internal class BuilderToAllImplementationsBinding : BuilderBindingBase
{
private IEnumerable<Assembly> assemblies;
private readonly IEnumerable<Assembly> assemblies;
public BuilderToAllImplementationsBinding(Type serviceType, IEnumerable<Assembly> assemblies)
: base(serviceType)

View File

@ -4,7 +4,7 @@ namespace StyletIoC.Internal.Builders
{
internal class BuilderTypeBinding : BuilderBindingBase
{
private Type implementationType;
private readonly Type implementationType;
public BuilderTypeBinding(Type serviceType, Type implementationType)
: base(serviceType)

View File

@ -7,7 +7,6 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
@ -16,6 +15,7 @@ namespace StyletIoC.Internal
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1611:ElementParametersMustBeDocumented", Justification = "Internal class, but some documentation added for readability. StyleCop ignores 'Internal only' setting if some documentation exists on member")]
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1615:ElementReturnValueMustBeDocumented", Justification = "Internal class, but some documentation added for readability. StyleCop ignores 'Internal only' setting if some documentation exists on member")]
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1618:GenericTypeParametersMustBeDocumented", Justification = "Internal class, but some documentation added for readability. StyleCop ignores 'Internal only' setting if some documentation exists on member")]
// ReSharper disable once RedundantExtendsListEntry
internal class Container : IContainer, IRegistrationContext
{
/// <summary>
@ -51,7 +51,7 @@ namespace StyletIoC.Internal
/// </summary>
public event EventHandler Disposing;
private bool disposed = false;
private bool disposed;
/// <summary>
/// Compile all known bindings (which would otherwise be compiled when needed), checking the dependency graph for consistency
@ -401,7 +401,7 @@ namespace StyletIoC.Internal
// {
// this.registrationContext = registrationContext;
// }
var ctorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { typeof(IRegistrationContext) });
var ctorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] { typeof(IRegistrationContext) });
var ilGenerator = ctorBuilder.GetILGenerator();
// Load 'this' and the registration context onto the stack
ilGenerator.Emit(OpCodes.Ldarg_0);
@ -413,7 +413,7 @@ namespace StyletIoC.Internal
// These are needed by all methods, so get them now
// IRegistrationContext.GetTypeOrAll(Type, string)
// IRegistrationContext extends ICreator, and it's ICreator that actually implements this
var containerGetMethod = typeof(IContainer).GetMethod("GetTypeOrAll", new Type[] { typeof(Type), typeof(string) });
var containerGetMethod = typeof(IContainer).GetMethod("GetTypeOrAll", new[] { typeof(Type), typeof(string) });
// Type.GetTypeFromHandler(RuntimeTypeHandle)
var typeFromHandleMethod = typeof(Type).GetMethod("GetTypeFromHandle");

View File

@ -4,6 +4,8 @@ using System.Linq.Expressions;
namespace StyletIoC.Internal.Creators
{
using System.Diagnostics;
/// <summary>
/// Knows how to create an instance of an abstract factory (generated by Container.GetFactoryForType)
/// </summary>
@ -23,6 +25,7 @@ namespace StyletIoC.Internal.Creators
public Expression GetInstanceExpression(ParameterExpression registrationContext)
{
var ctor = this.abstractFactoryType.GetConstructor(new[] { typeof(IRegistrationContext) });
Debug.Assert(ctor != null);
var construction = Expression.New(ctor, registrationContext);
return construction;
}

View File

@ -13,7 +13,7 @@ namespace StyletIoC.Internal.Creators
public virtual Type Type { get; protected set; }
protected IRegistrationContext ParentContext { get; set; }
public CreatorBase(IRegistrationContext parentContext)
protected CreatorBase(IRegistrationContext parentContext)
{
this.ParentContext = parentContext;
}

View File

@ -1,10 +1,6 @@
using StyletIoC.Creation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace StyletIoC.Internal.Creators
{

View File

@ -55,7 +55,7 @@ namespace StyletIoC.Internal.Creators
{
ctor = ctorsWithAttribute[0];
var key = ctorsWithAttribute[0].GetCustomAttribute<InjectAttribute>(true).Key;
var cantResolve = ctor.GetParameters().Where(p => !this.ParentContext.CanResolve(p.ParameterType, key) && !p.HasDefaultValue).FirstOrDefault();
var cantResolve = ctor.GetParameters().FirstOrDefault(p => !this.ParentContext.CanResolve(p.ParameterType, key) && !p.HasDefaultValue);
if (cantResolve != null)
throw new StyletIoCFindConstructorException(String.Format("Found a constructor with [Inject] on type {0}, but can't resolve parameter '{1}' (of type {2}, and doesn't have a default value).", this.Type.GetDescription(), cantResolve.Name, cantResolve.ParameterType.GetDescription()));
}

View File

@ -1,9 +1,6 @@
using StyletIoC.Creation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StyletIoC.Internal.RegistrationCollections
{

View File

@ -33,7 +33,7 @@ namespace StyletIoC.Internal.RegistrationCollections
lock (this.registrationsLock)
{
// Should have been caught by SingleRegistration.AddRegistration
Debug.Assert(!this.registrations.Any(x => x.Type == registration.Type));
Debug.Assert(this.registrations.All(x => x.Type != registration.Type));
this.registrations.Add(registration);
return this;
}

View File

@ -12,7 +12,7 @@ namespace StyletIoC.Internal.Registrations
{
private readonly Type funcType;
private readonly Func<IRegistrationContext, object> generator;
private IRegistration delegateRegistration;
private readonly IRegistration delegateRegistration;
public Type Type
{

View File

@ -6,6 +6,8 @@ using System.Threading;
namespace StyletIoC.Internal.Registrations
{
using System.Diagnostics;
/// <summary>
/// Knows how to generate an IEnumerable{T}, which contains all implementations of T
/// </summary>
@ -54,6 +56,7 @@ namespace StyletIoC.Internal.Registrations
var instanceExpressions = this.parentContext.GetAllRegistrations(this.Type.GenericTypeArguments[0], this.Key, false).Select(x => x.GetInstanceExpression(registrationContext)).ToArray();
var listCtor = this.Type.GetConstructor(new[] { typeof(int) }); // ctor which takes capacity
Debug.Assert(listCtor != null);
var listNew = Expression.New(listCtor, Expression.Constant(instanceExpressions.Length));
Expression list = instanceExpressions.Any() ? (Expression)Expression.ListInit(listNew, instanceExpressions) : listNew;

View File

@ -15,7 +15,7 @@ namespace StyletIoC.Internal.Registrations
private readonly object generatorLock = new object();
protected Func<IRegistrationContext, object> Generator { get; set; }
public RegistrationBase(ICreator creator)
protected RegistrationBase(ICreator creator)
{
this.Creator = creator;
}

View File

@ -1,9 +1,6 @@
using StyletIoC.Internal.Builders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StyletIoC
{

View File

@ -190,6 +190,9 @@ namespace Stylet
if (this.Validator == null)
throw new InvalidOperationException("Can't run validation if a validator hasn't been set");
if (propertyName == null)
propertyName = String.Empty;
// To allow synchronous calling of this method, we need to resume on the ThreadPool.
// Therefore, we might resume on any thread, hence the need for a lock
var newErrorsRaw = await this.Validator.ValidatePropertyAsync(propertyName).ConfigureAwait(false);

View File

@ -161,6 +161,7 @@ namespace Stylet
}
// This gets itself retained by the window, by registering events
// ReSharper disable once ObjectCreationAsStatement
new WindowConductor(window, viewModel);
return window;
@ -171,8 +172,8 @@ namespace Stylet
if (Application.Current == null)
return null;
var active = Application.Current.Windows.OfType<Window>().Where(x => x.IsActive).FirstOrDefault() ?? Application.Current.MainWindow;
return active == window ? null : active;
var active = Application.Current.Windows.OfType<Window>().FirstOrDefault(x => x.IsActive) ?? Application.Current.MainWindow;
return ReferenceEquals(active, window) ? null : active;
}
private class WindowConductor : IChildDelegate

View File

@ -84,12 +84,11 @@ namespace Stylet.Xaml
return new CommandAction((DependencyObject)valueService.TargetObject, this.Method, nullTarget, actionNotFound);
}
var propertyAsEventInfo = valueService.TargetProperty as EventInfo;
if (propertyAsEventInfo != null)
if (valueService.TargetProperty is EventInfo)
{
var nullTarget = this.NullTarget == ActionUnavailableBehaviour.Default ? ActionUnavailableBehaviour.Enable : this.NullTarget;
var actionNotFound = this.ActionNotFound == ActionUnavailableBehaviour.Default ? ActionUnavailableBehaviour.Throw : this.ActionNotFound;
var ec = new EventAction((DependencyObject)valueService.TargetObject, propertyAsEventInfo, this.Method, nullTarget, actionNotFound);
var ec = new EventAction((DependencyObject)valueService.TargetObject, this.Method, nullTarget, actionNotFound);
return ec.GetDelegate();
}

View File

@ -22,8 +22,8 @@ namespace Stylet.Xaml
/// </summary>
public Visibility TrueVisibility
{
get { return (Visibility)GetValue(TrueVisibilityProperty); }
set { SetValue(TrueVisibilityProperty, value); }
get { return (Visibility)this.GetValue(TrueVisibilityProperty); }
set { this.SetValue(TrueVisibilityProperty, value); }
}
/// <summary>
@ -37,8 +37,8 @@ namespace Stylet.Xaml
/// </summary>
public Visibility FalseVisibility
{
get { return (Visibility)GetValue(FalseVisibilityProperty); }
set { SetValue(FalseVisibilityProperty, value); }
get { return (Visibility)this.GetValue(FalseVisibilityProperty); }
set { this.SetValue(FalseVisibilityProperty, value); }
}
/// <summary>
@ -66,6 +66,7 @@ namespace Stylet.Xaml
{
result = (bool)value;
}
// ReSharper disable once CanBeReplacedWithTryCastAndCheckForNull
else if (value is IEnumerable)
{
result = ((IEnumerable)value).GetEnumerator().MoveNext();
@ -82,7 +83,7 @@ namespace Stylet.Xaml
// Easiest is just to try it and see
try
{
result = !value.Equals(System.Convert.ChangeType((object)0, value.GetType()));
result = !value.Equals(System.Convert.ChangeType(0, value.GetType()));
}
catch
{

View File

@ -22,8 +22,8 @@ namespace Stylet.Xaml
/// </summary>
public string Name
{
get { return (string)GetValue(NameProperty); }
set { SetValue(NameProperty, value); }
get { return (string)this.GetValue(NameProperty); }
set { this.SetValue(NameProperty, value); }
}
/// <summary>
@ -37,8 +37,8 @@ namespace Stylet.Xaml
/// </summary>
public Action<string, string> Logger
{
get { return (Action<string, string>)GetValue(LoggerProperty); }
set { SetValue(LoggerProperty, value); }
get { return (Action<string, string>)this.GetValue(LoggerProperty); }
set { this.SetValue(LoggerProperty, value); }
}
/// <summary>

View File

@ -22,8 +22,8 @@ namespace Stylet.Xaml
/// </summary>
public bool Invert
{
get { return (bool)GetValue(InvertProperty); }
set { SetValue(InvertProperty, value); }
get { return (bool)this.GetValue(InvertProperty); }
set { this.SetValue(InvertProperty, value); }
}
/// <summary>
@ -49,7 +49,7 @@ namespace Stylet.Xaml
if (values == null || values.Length == 0)
return null;
var first = values.FirstOrDefault();
var result = values.Skip(1).All(x => first.Equals(x));
var result = values.Skip(1).All(x => x.Equals(first));
return this.Invert ? !result : result;
}

View File

@ -19,17 +19,12 @@ namespace Stylet.Xaml
/// <summary>
/// View whose View.ActionTarget we watch
/// </summary>
private DependencyObject subject;
/// <summary>
/// Property on the WPF element we're returning a delegate for
/// </summary>
private EventInfo targetProperty;
private readonly DependencyObject subject;
/// <summary>
/// The MyMethod in {s:Action MyMethod}, this is what we call when the event's fired
/// </summary>
private string methodName;
private readonly string methodName;
/// <summary>
/// MethodInfo for the method to call. This has to exist, or we throw a wobbly
@ -42,11 +37,10 @@ namespace Stylet.Xaml
/// Initialises a new instance of the <see cref="EventAction"/> class
/// </summary>
/// <param name="subject">View whose View.ActionTarget we watch</param>
/// <param name="targetProperty">Property on the WPF element we're returning a delegate for</param>
/// <param name="methodName">The MyMethod in {s:Action MyMethod}, this is what we call when the event's fired</param>
/// <param name="targetNullBehaviour">Behaviour for it the relevant View.ActionTarget is null</param>
/// <param name="actionNonExistentBehaviour">Behaviour for if the action doesn't exist on the View.ActionTarget</param>
public EventAction(DependencyObject subject, EventInfo targetProperty, string methodName, ActionUnavailableBehaviour targetNullBehaviour, ActionUnavailableBehaviour actionNonExistentBehaviour)
public EventAction(DependencyObject subject, string methodName, ActionUnavailableBehaviour targetNullBehaviour, ActionUnavailableBehaviour actionNonExistentBehaviour)
{
if (targetNullBehaviour == ActionUnavailableBehaviour.Disable)
throw new ArgumentException("Setting NullTarget = Disable is unsupported when used on an Event");
@ -54,7 +48,6 @@ namespace Stylet.Xaml
throw new ArgumentException("Setting ActionNotFound = Disable is unsupported when used on an Event");
this.subject = subject;
this.targetProperty = targetProperty;
this.methodName = methodName;
this.targetNullBehaviour = targetNullBehaviour;
this.actionNonExistentBehaviour = actionNonExistentBehaviour;

View File

@ -82,7 +82,7 @@ namespace Stylet.Xaml
{
if (Execute.InDesignMode)
{
var bindingExpression = BindingOperations.GetBindingExpression(d, View.ModelProperty);
var bindingExpression = BindingOperations.GetBindingExpression(d, ModelProperty);
string text;
if (bindingExpression == null)
text = "View for [Broken Binding]";
@ -90,7 +90,7 @@ namespace Stylet.Xaml
text = String.Format("View for child ViewModel on {0}", bindingExpression.DataItem.GetType().Name);
else
text = String.Format("View for {0}.{1}", bindingExpression.DataItem.GetType().Name, bindingExpression.ResolvedSourcePropertyName);
View.SetContentProperty(d, new System.Windows.Controls.TextBlock() { Text = text });
SetContentProperty(d, new System.Windows.Controls.TextBlock() { Text = text });
}
else
{

View File

@ -44,59 +44,57 @@ namespace StyletUnitTests
private DependencyObject subject;
private Target target;
private EventInfo eventInfo;
[SetUp]
public void SetUp()
{
this.target = new Target();
this.subject = new Button();
this.eventInfo = typeof(Button).GetEvent("Click");
View.SetActionTarget(this.subject, this.target);
}
[Test]
public void ThrowsIfNullTargetBehaviourIsDisable()
{
Assert.Throws<ArgumentException>(() => new EventAction(this.subject, this.eventInfo, "DoSomething", ActionUnavailableBehaviour.Disable, ActionUnavailableBehaviour.Enable));
Assert.Throws<ArgumentException>(() => new EventAction(this.subject, "DoSomething", ActionUnavailableBehaviour.Disable, ActionUnavailableBehaviour.Enable));
}
[Test]
public void ThrowsIfNonExistentActionBehaviourIsDisable()
{
Assert.Throws<ArgumentException>(() => new EventAction(this.subject, this.eventInfo, "DoSomething", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Disable));
Assert.Throws<ArgumentException>(() => new EventAction(this.subject, "DoSomething", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Disable));
}
[Test]
public void ThrowsIfTargetNullBehaviourIsThrowAndTargetBecomesNull()
{
var cmd = new EventAction(this.subject, this.eventInfo, "DoSomething", ActionUnavailableBehaviour.Throw, ActionUnavailableBehaviour.Enable);
var cmd = new EventAction(this.subject, "DoSomething", ActionUnavailableBehaviour.Throw, ActionUnavailableBehaviour.Enable);
Assert.Throws<ActionTargetNullException>(() => View.SetActionTarget(this.subject, null));
}
[Test]
public void ThrowsIfActionNonExistentBehaviourIsThrowAndActionIsNonExistent()
{
var cmd = new EventAction(this.subject, this.eventInfo, "DoSomething", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Throw);
var cmd = new EventAction(this.subject, "DoSomething", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Throw);
Assert.Throws<ActionNotFoundException>(() => View.SetActionTarget(this.subject, new Target2()));
}
[Test]
public void ThrowsIfMethodHasTooManyArguments()
{
Assert.Throws<ActionSignatureInvalidException>(() => new EventAction(this.subject, this.eventInfo, "DoSomethingWithTooManyArgs", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Enable));
Assert.Throws<ActionSignatureInvalidException>(() => new EventAction(this.subject, "DoSomethingWithTooManyArgs", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Enable));
}
[Test]
public void ThrowsIfMethodHasBadParameter()
{
Assert.Throws<ActionSignatureInvalidException>(() => new EventAction(this.subject, this.eventInfo, "DoSomethingWithBadArgument", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Enable));
Assert.Throws<ActionSignatureInvalidException>(() => new EventAction(this.subject, "DoSomethingWithBadArgument", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Enable));
}
[Test]
public void InvokingCommandDoesNothingIfTargetIsNull()
{
var cmd = new EventAction(this.subject, this.eventInfo, "DoSomething", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Enable);
var cmd = new EventAction(this.subject, "DoSomething", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Enable);
View.SetActionTarget(this.subject, null);
cmd.GetDelegate().DynamicInvoke(null, null);
}
@ -104,7 +102,7 @@ namespace StyletUnitTests
[Test]
public void InvokingCommandDoesNothingIfActionIsNonExistent()
{
var cmd = new EventAction(this.subject, this.eventInfo, "DoSomething", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Enable);
var cmd = new EventAction(this.subject, "DoSomething", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Enable);
View.SetActionTarget(this.subject, new Target2());
cmd.GetDelegate().DynamicInvoke(null, null);
}
@ -112,7 +110,7 @@ namespace StyletUnitTests
[Test]
public void InvokingCommandCallsMethod()
{
var cmd = new EventAction(this.subject, this.eventInfo, "DoSomething", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Enable);
var cmd = new EventAction(this.subject, "DoSomething", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Enable);
cmd.GetDelegate().DynamicInvoke(null, null);
Assert.True(this.target.DoSomethingCalled);
}
@ -120,7 +118,7 @@ namespace StyletUnitTests
[Test]
public void InvokingCommandCallsMethodWithEventArgs()
{
var cmd = new EventAction(this.subject, this.eventInfo, "DoSomethingWithEventArgs", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Enable);
var cmd = new EventAction(this.subject, "DoSomethingWithEventArgs", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Enable);
var arg = new RoutedEventArgs();
cmd.GetDelegate().DynamicInvoke(null, arg);
Assert.AreEqual(arg, this.target.EventArgs);