x:Name attribute does not always create member or field variable
Adding an x:Name attribute to a XAML element normally results in a member variable being added to the backing class that can then be accessed using normal code. When the element in question is part of the DataTemplate, the field does not get created.
I can sort of understand that the DataTemplate is making this a special case but can anyone explain the underlying principle to me? Also what are the options for getting access to the object within .NET Code?
<dataControls:DataForm x:Name="CompanyDetail" CurrentItem="{Binding CurrentItem}" AutoGenerateFields="False">
<dataControls:DataForm.EditTemplate>
<DataTemplate>
<StackPanel dataControls:DataField.IsFieldGroup="True">
<dataControls:DataField Label="About">
<Border Height="150" Style="{StaticResource HtmlPlaceHolderBorderStyle}" Width="298" VerticalAlignment="Top">
<telerik:RadHtmlPlaceholder x:Name="uxAboutHtml" 开发者_StackOverflow中文版x:FieldModifier="Public" HtmlSource="{Binding About, Mode=TwoWay}"/>
</Border>
</dataControls:DataField>
</StackPanel>
</DataTemplate>
</dataControls:DataForm.EditTemplate>
</dataControls:DataForm>
You can use the FrameworkElement.FindName("objectName") method on the parent of the DataTemplate e.g. var uxAboutHtml = CompanyDetail.FindName("uxAboutHtml");
to get a reference to the object. The downside to this is that paramater passed to FindName does not end up being strongly typed with the XAML x:Name"objectName" attribute.
I have changed tack on this and am now referencing the underlying object that the control is being bound to, which is probably a better way to go.
var htmlContent = (CompanyViewModel)CompanyDetail.CurrentItem;
精彩评论