c# - ObservableCollection<T> on xaml -
i'm working on customconverter
on wpf. generic convertion.
reading on blog, found way simplify xaml.
so converter looks this:
public customconverter : markupextension, imultivalueconverter { public parameterscollection parameters { get; set; } public object convert(object[] values, type targettype, object parameter, system.globalization.cultureinfo culture) { if(parameters == null) return binding.donothing; //convertion logic //... } public override object providevalue(iserviceprovider serviceprovider) { return new customconverter(); } } public class parameterscollection : observablecollection<object> { }
and in xaml file, have following:
<usercontrol xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:primitives="clr-namespace:system;assembly=mscorlib" xmlns:converter="clr-namespace:ns.converters"> <label> <label.visibility> <multibinding> <converter:customconverter> <converter:customconverter.parameters> <converter:parameterscollection> <primitives:string>param1</primitives:string> ... </converter:parameterscollection> </converter:customconverter.parameters> </converter:customconverter> </multibinding> <!--bindings start here --> </label.visibility> </label> </usercontrol>
so when debbuging code, parameters
property empty (null), xaml not populating collection. question is, how popultate parameters using xaml, no c# code.
if put breakpoint on first line of convert
method, you'll find parameters
null
. that's because never initialize it. solution initialize property in constructor (or right in declaration, if you're in c#6).
parameters
doesn't need observablecollection<t>
, because nobody ever bind it, , doesn't need non-generic subclass either. lastly, providevalue()
should provide actual instance has parameters
given xaml. if return new instance empty parameters
collection, won't have parameters
. providevalue()
called after you're created , initialized. purpose isn't provide new instance of own class, markup extensions staticresource
or dynamicresource
take parameters , use create or retrieve instance of other themselves.
public class customconverter : markupextension, imultivalueconverter { public customconverter() { parameters = new list<object>(); } public list<object> parameters { get; set; } public object convert(object[] values, type targettype, object parameter, system.globalization.cultureinfo culture) { if (parameters == null) return binding.donothing; // returns something, testing // replace own convertion logic. return string.join(";", parameters); } public object[] convertback(object value, type[] targettypes, object parameter, cultureinfo culture) { return null; } public override object providevalue(iserviceprovider serviceprovider) { return this; } }
Comments
Post a Comment