开发者

How to work with template member properties

开发者 https://www.devze.com 2023-04-06 04:32 出处:网络
Before anything else, I do apologize for the following verbose question. Since I\'m new to WPF, I decided to explain more in order to probably get more tips!

Before anything else, I do apologize for the following verbose question. Since I'm new to WPF, I decided to explain more in order to probably get more tips!


I have a UserControl like:

<UserControl x:Class="MyNamespace.MyUserControl2"...
             xmlns:local="clr-namespace:MyNamespace"
             Style="{DynamicResource ResourceKey=style1}">
    <UserControl.Resources>
        <Style x:Key="style1" TargetType="{x:Type UserControl}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type UserControl}">
                        ...
                        <local:MyUserControl1 x:Name="myUserControl1" .../>
                        ...
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </UserControl.Resources>
</UserControl>

To access to the myUserControl1 from the code behind, I used a property.

private MyUserControl1 _myUserControl1;
private MyUserControl1 myUserControl1
{
    get
    {
        if (_myUserControl1 == null)
            _myUserControl1 = this.Template.FindName("myUserControl1", this) as MyUserControl1;

        return _myUserControl1;
    }
}

(Is this a good approach to access a template member?)

On the other hand, there is a dependency property in MyUserControl2 class (say DP1) that is responsible for modifying one of myUserControl1 dependency properties. (Say 开发者_开发技巧SomeProperty)

private static void IsDP1PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var instance = d as MyUserControl2;
    if (instance != null)
    {
        instance.myUserControl1.SomeProperty = function(e.NewValue);
    }
}

When I tried to run the above code, I noticed that instance.myUserControl1 is null. So I treated it like so:

if (instance != null && instance.myUserControl1 != null)
{
    instance.myUserControl1.SomeProperty = function(e.NewValue);
}

Although this approach solved the issue, it causes myUserControl1.SomeProperty to remain uninitialized. So, I put the following code snippet at the loaded event to resolve it:

private void MyUserControl2_Loaded(object sender, RoutedEventArgs e)
{
    this.myUserControl1.SomeProperty = function(DP1);
}

After that, I encountered another problem!

When I set some value to DP1 using setter attribute of a style, I received a null reference exception that says myUserControl1 property is still null at the loaded event. How can I work around it? -Thanks.


I guess you haven't still a clear idea about WPF.

You are hitting so many troubles because your approach is much "winforms-like", than functional. WPF makes your life harder if you insist using it in a imperative manner.

First off, the template represents a function to instructs the WPF engine on how to create the actual visual tree during the run time. You should use the name as reference within a template ONLY inside the hosting control (i.e. MyUserControl2), and getting the instance reference from within the OnApplyTemplate method. Nowhere else.

Example:

private MyUserControl1 _myUserControl1;

public override void OnApplyTemplate()
{
  this._myUserControl1 = this.GetTemplateChild("myUserControl1") as MyUserControl1;
  //here you should check whether the instance is actually set
}

The reference of any control is hosted should kept as private: no protected/internal/public exposition of any of the hosted controls.

Second point: how to bind two properties together.

Your goal is to "bind" a property of a control with another exposed by the hosted one. This task is absolutely normal, and it is one of the best features offered by WPF.

Supposing that the two properties share the same type, thus can be bound directly. Within your xaml:

    <ControlTemplate TargetType="{x:Type UserControl}">
         ...
       <local:MyUserControl1 x:Name="myUserControl1" 
   SomeProperty="{Binding Path=DP1, RelativeSource={RelativeSource Mode=TemplatedParent}}"
   .../>
         ...
    </ControlTemplate>

Note that: (1) SomeProperty must be a DependencyProperty, (2) must be writable, (3) DP1 must be also a DP, or -at least- notify any change via the INotifyPropertyChanged pattern.

The syntax depicted binds normally: SomeProperty = DP1, but not vice versa. If you need an bidirectional mapping, you should add "Mode=TwoWay" inside the "Binding" clause.

If you want to customize the function that maps the two properties, simply define your own converter via the IValueConverter interface, then declare it in the xaml.

Here you will find several useful info: http://msdn.microsoft.com/en-us/library/ms752347.aspx

Cheers

0

精彩评论

暂无评论...
验证码 换一张
取 消