In XAML I do it like this:
<Button Style="{StaticResource NavigationBackButtonNormalStyle}" />
How do I do the same thing in code-behind?
The page-level Resources object has the ability to find local, app-level, static, and theme resources. This means you simply do this:
foo2.Style = this.Resources["NavigationBackButtonNormalStyle"] as Style;
Best of luck!
During design-time, it seems that trying to resolve a "system resource" using Resources[key] will fail to find the resource and will return null. For example, to get the base Style for a TextBox using Resources[typeof(TextBox)] will return null.
Instead, use TryFindResource(key) since this will first try Resources[key] and then will otherwise try searching through the "system resources" and will return what you're looking for (as per MSDN and Reference Source).
In other words, try this instead:
var style = Application.Current.TryFindResource(key) as Style;
Try with this
Application.Current.Resources["key"]
Here's a generic helper class that can be used. The advantage of going this route, is tha tyou will be able to use the same helper to get other types of resources (like Brushes, or DataTemplate for example)
public static class Helper
{
public static T Get<T>(string resourceName) where T : class
{
return Application.Current.TryFindResource(resourceName) as T;
}
}
And how you would use in code:
yourButton.Style = Helper.Get<Style>("NavigationBackButtonNormalStyle");
And if you wanted to get a brush resource you'd use
ItemTemplate = Helper.Get<DataTemplate>("MyDataTemplate");
If you are working in the ViewModel, you wont be able to use the answer above.
To bring up to date the answer from Eternal21, you could so this:
public static T Get<T>(string resourceName)
{
try{
var success = Application.Current.Resources.TryGetValue(resourceName, out var outValue);
if(success && outValue is T)
{
return (T)outValue;
}
else
{
return default(T);
}
}
catch
{
return default(T);
}
}
Note the where clause is missing here. I didn't want to restrict it to classes, so I could use it with Color too which is a struct... so removed it.
Related
Core Question:
I have a generic interface IValidatingAttribute<T>, which creates the contract bool IsValid(T value); The interface is implemented by a variety of Attributes, which all serve the purpose of determining if the current value of said Field or Property they decorate is valid per the interface spec that I'm dealing with. What I want to do is create a single validation method that will scan every field and property of the given model, and if that field or property has any attributes that implement IValidatingAttribute<T>, it should validate the value against each of those attributes. So, using reflection I have the sets of fields and properties, and within those sets I can get the list of attributes. How can I determine which attributes implement IValidatingAttribute and then call IsValid(T value)?
background:
I am working on a library project that will be used to develop a range of later projects against the interface for a common third party system. (BL Server, for those interested)
BL Server has a wide range of fairly arcane command structures that have varying validation requirements per command and parameter, and then it costs per transaction to call these commands, so one of the library requirements is to easily define the valdiation requirements at the model level to catch invalid commands before they are sent. It is also intended to aid in the development of later projects by allowing developers to catch invalid models without needing to set up the BL server connections.
Current Attempt:
Here's where I've gotten so far (IsValid is an extension method):
public interface IValidatingAttribute<T>
{
bool IsValid(T value);
}
public static bool IsValid<TObject>(this TObject sourceObject) where TObject : class, new()
{
var properties = typeof(TObject).GetProperties();
foreach (var prop in properties)
{
var attributeData = prop.GetCustomAttributesData();
foreach (var attribute in attributeData)
{
var attrType = attribute.AttributeType;
var interfaces = attrType.GetInterfaces().Where(inf => inf.IsGenericType).ToList();
if (interfaces.Any(infc => infc.Equals(typeof(IValidatingAttribute<>))))
{
var value = prop.GetValue(sourceObject);
//At this point, I know that the current attribute implements 'IValidatingAttribute<>', but I don't know what T is in that implementation.
//Also, I don't know what data type 'value' is, as it's currently boxed as an object.
//The underlying type to value will match the expected T in IValidatingAttribute.
//What I need is something like the line below:
if (!(attribute as IValidatingAttribute<T>).IsValid(value as T)) //I know this condition doesn't work, but it's what I'm trying to do.
{
return false;
}
}
}
return true;
}
}
Example usage:
Just to better explain what I am trying to achieve:
public class SomeBLRequestObject
{
/// <summary>
/// Required, only allows exactly 2 alpha characters.
/// </summary>
[MinCharacterCount(2), MaxCharacterCount(2), IsRequired, AllowedCharacterSet(CharSets.Alpha))]
public string StateCode {get; set;}
}
And then, later on in code:
...
var someBLObj = SomeBLRequestObjectFactory.Create();
if(!someBLObj.IsValid())
{
throw new InvalidObjectException("someBLObj is invalid!");
}
Thank you, I'm really looking for a solution to the problem as it stands, but I'm more than willing to listen if somebody has a viable alternative approach.
I'm trying to go generic extension method with this because there are literally hundreds of the BL Server objects, and I'm going with attributes because each of these objects can have upper double digit numbers of properties, and it's going to make things much, much easier if the requirements for each object are backed in and nice and readable for the next developer to have to use this thing.
Edit
Forgot to mention : This Question is the closest I've found, but what I really need are the contents of \\Do Something in TcKs's answer.
Well, after about 6 hours and a goods nights sleep, I realized that I was over-complicating this thing. Solved it with the following (ExtValidationInfo is the class that the below two extensions are in.):
Jon Skeet's answer over here pointed me at a better approach, although it still smells a bit, this one at least works.
public static bool IsValid<TObject>(this TObject sourceObject) where TObject : class, new()
{
var baseValidationMethod = typeof(ExtValidationInfo).GetMethod("ValidateProperty", BindingFlags.Static | BindingFlags.Public);
var properties = TypeDataHandler<TObject>.Properties;
foreach (var prop in properties)
{
var attributes = prop.GetCustomAttributes(typeof(IValidatingAttribute<>)).ToList();
if (!attributes.Any())
{
continue; // No validators, skip.
}
var propType = prop.PropertyType;
var validationMethod = baseValidationMethod.MakeGenericMethod(propType);
var propIsValid = validationMethod.Invoke(null, prop.GetValue(sourceObject), attributes);
if(!propIsValid)
{
return false;
}
}
return true;
}
public static bool ValidateProperty<TPropType>(TPropType value, List<IValidatingAttribute<TPropType>> validators)
{
foreach (var validator in validators)
{
if (!validator.IsValid(value))
{
return false;
}
}
return true;
}
We use a lot of Generics in our code. For example ICommandHandler<T> where T is ICommand, ICommandValidator<T> etc etc
Not everything has a ICommandValidator implementation. I was looking to use the NullObject pattern so that I could provide a fall back option to avoid having to test if validator is null.
For example
public class NullObjectCommandValidator : ICommandValidator<ICommand>
{
public bool IsValid(ICommand command)
{
return true;
}
}
We register all like:
builder.RegisterAssemblyTypes(assemblies)
.AsClosedTypesOf(typeof(ICommandValidator<>))
.InstancePerHttpRequest();
I was hoping to be able to register the NullObjectCommandValidator as a default for any ICommandValidator that didn't have a concrete implementation using a process like registering all other ICommandValidators<> and then registering the Null version at the end and preserving existing defaults.
Is something like this possible?
You should change NullObjectCommandValidator to a generic type NullObjectCommandValidator<TCommand>. This way you can register it as follows:
builder.RegisterGeneric(typeof(NullObjectCommandValidator<>))
.As(typeof(ICommandValidator<>));
NullObjectCommandValidator<TCommand> looks like this:
public class NullObjectCommandValidator<TCommand> : ICommandValidator<TCommand>
{
public bool IsValid(TCommand command)
{
return true;
}
}
Got a class with a method that takes an object and loops through it, assigning the values of the object to the class. This can happen quite a bit in the application and I was wondering if there is an efficient and preferably language agnostic syntax to validate the property name of the object exists and confirm the value type before assigning to the class? I'm going to need to export this code to at least flash and javascript, possibly others to follow later. I need to keep the method generic because it lives in a base class. Something along the lines below:
public function updateProperties(propsObj:Object):void {
for (var prop in propsObj) {
if (/* this has prop && typeof propsObj[prop] == typeof this[prop] */) {
this[prop] = propsObj[prop];
}
}
}
New to Haxe, so I'm having some trouble finding the family of methods for this kind of thing. Reflect seems to have methods close to what I'm looking for, but a lot of the methods look like they may be overkill for what I need, was hoping for some insight.
This seems to work.
public function updateProperties(props:Dynamic) {
for (prop in Reflect.fields(props)) {
if (Reflect.hasField(this, prop)) {
Reflect.setProperty(this, prop, Reflect.getProperty(props, prop));
} else {
trace("cannot set property " + prop + " on " + this);
}
}
}
Im wondering if its possible to reuse my overload of the Sort(Comparison) method to sort both labels and textboxes by tabIndex. Ive already tried and i couldnt get it to work. Any help would be appreciated.
foreach(Control control in gbUserInputs.Controls)
{
if (control is Label)
{
inputLabels.Add((Label)control);
}
if (control is TextBox)
{
inputTxtboxes.Add((TextBox)control);
}
}
Sort method call(this doesnt work).
inputLabels.Sort(sortMyInputs<Label>);
Overload of sort method.
private static int sortMyInputs<T>(T entry1, T entry2)
{
return entry1.TabIndex.CompareTo(entry2.TabIndex);
}
You shouldn't be making a generic method:
private static int CompareLabels(Label entry1, Label entry2)
{
return entry1.TabIndex.CompareTo(entry2.TabIndex);
}
The point of a generic delegate is to allow it to hold methods of different concrete types; not to allow it to hold methods that are themselves generic.
If you want to reuse your method, you can modify it to take Control (which both TextBox and Label inherit); you would still be able to pass it to List<Label>.Sort because of delegate covariance.
If you're using .Net < 4, which doesn't have delegate covariance, you can do it your way by adding a constraint to the method so that it knows what T can be:
private static int CompareLabels<T>(T entry1, T entry2) where T : Control
{
return entry1.TabIndex.CompareTo(entry2.TabIndex);
}
You can also simply replace all of your code with one line of LINQ:
inputLabels = gbUserInputs.Controls.OfType<Label>()
.OrderBy(c => c.TabIndex)
.ToList();
I have a simple class that I want to implement INotifyPropertyChanged. I don't need to have a private version of this property. The class is being passed via a WCF service and a Silverlight client.
My question: Is it OK to structure the get accessor this way? Just does not seem right to me.
public ProjectID
{
get
{
return this.ProjectID;
}
set
{
ProjectID = value;
NotifyPropertyChanged("ProjectID");
}
}
I think the code above will throw a stack overflow exception, you may have to implement a member to support the interface you want to
That would result in a StackOverflowException, because the get property would keep recursively calling itself.