c# - Setting Binding in code to Text property on TextBox WPF not working -
i have following xaml in usercontrol:
<stackpanel orientation="horizontal" name="spcontainer"> <textblock x:name="tblabelbefore" minwidth="50" text="{binding labelbefore}"></textblock> <textbox name="txtkey" minwidth="120"></textbox> <textblock name="tbvalue" minwidth="50"></textblock> </stackpanel>
next want set binding dynamically text property on textbox-txtkey from proxy class.
i following:
mdlookup lok = selectedobject mdlookup; string bnd = "model."+ lok.name +".value"; binding binding = new binding(bnd); binding.updatesourcetrigger = updatesourcetrigger.propertychanged; //binding.validatesondataerrors = true; //binding.notifyonvalidationerror = true; binding.mode = bindingmode.twoway; lok.txtkey.setbinding(textbox.textproperty, binding);
here lok instance of user control. , txtkey property in usercontrol of type textbox returns txtkey element:
[xmlignore] [browsable(false)] [designerserializationvisibility(designerserializationvisibility.hidden)] public textbox txtkey { { return this.txtkey; } set { this.txtkey = value; } }
if put:
lok.txtkey.text = "some text"
this works. code setting binding works in constructor of user control. here doesn't. idea why?
additional: have ovverided shouldserializecontent
public override bool shouldserializecontent() { return false; }
the point serialize xaml multiple controls in databasebase , afterwards dynamically load , set datacontext.
if txtkey
name of textbox
inside usercontrol
, having problems because cannot access elements inside controls other controls. although can access named controls inside usercontrol
defined in, not mean publicly available outside control.
if txtkey
dependencyproperty
of type usercontrol
, find usercontrol
class not have text
property in , still not able bind it. cannot answer further without providing further information. in these cases listed above, should have received sort of compilation or binding error... check output window in visual studio errors.
update >>>
in order achieve want, need define dependencyproperty
in usercontrol
. won't show how here there millions of online examples... let's name text
. change xaml in usercontrol
this:
<textbox name="txtkey" minwidth="120" text="{binding text, relativesource={relativesource ancestortype={x:type yourprefix:yourusercontrol}}}" />
then have publicly available property data bind or set externally update textbox.text
value:
<yourprefix:yourusercontrol text="{binding databoundtextpropertyoutsidecontrol}" />
or:
<yourprefix:yourusercontrol text="plain text string" />
or in code:
yourusercontrol yourusercontrol = new yourusercontrol(); yourusercontrol.text = "plain text string";
or:
... yourusercontrol.setbinding(yourusercontrol.textproperty, binding);
Comments
Post a Comment