WPF How do I evaluate a property to make binding

I'm doing a custom control for our company, and I want to define DataTemplate of elements into a ResourceDictionary, for more genericity and skin handling. My control has a ItemsSource property that contains all collection. I also have a DependencyProperty into my control that specificy the name of the property of current Item to bind on.

Some code :

<DataTemplate x:Key="VEGA_TokenTemplate">
  <Border x:Name="Bd" BorderBrush="{StaticResource VEGA_TokenBorderBrush}" BorderThickness="1" Background="{StaticResource VEGA_TokenBackgroundBrush}" Padding="1" Margin="1,5" HorizontalAlignment="Stretch" SnapsToDevicePixels="True">
    <Grid VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
      <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="20" />
      </Grid.ColumnDefinitions>
      <TextBlock Text="{Binding WHAT_HERE}" HorizontalAlignment="Stretch" VerticalAlignment="Center" />
      <Button Background="Transparent" Content="X" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="10" FontFamily="Berlin Sans FB" Grid.Column="1" Command="{Binding RelativeSource={RelativeSource AncestorType=local:TokenTextBox}, Path=TokenDeleteButtonCommand}"
      CommandParameter="{Binding WHAT_HERE}" IsEnabled="True" />
    </Grid>
  </Border>
</DataTemplate>

In this DataTemplate, I would like to replace the WHAT_HERE tag by the evaluation of my dependency property. For example, if I set "Email" on my dependency property, I would like the Binding to be like "Path=Email". However, I only have "Email" as litteral into my component. How can I do such a Binding ?

I hope I'm clear in my explainations...

Thank you


I would use Behaviors in this situation or attached properties. I am sure there are other variation of how you can accomplish this. But here is one way to give you an idea

//test interface and test class
public interface IProvidePropertyToBindTo
{
    string GetPropertyToBindTo();
}

public class TestChoosingPropertyToBind : IProvidePropertyToBindTo, INotifyPropertyChanged
{
    #region Fields
    public event PropertyChangedEventHandler PropertyChanged;
    private string _emailAddress;
    private string _name;
    private string _propertyName;
    #endregion Fields
    #region Properties
    public string EmailAddress
    {
        get { return _emailAddress; }
        set
        {
            if (_emailAddress == value) 
                return;
            _emailAddress = value;
            OnPropertyChanged();
        }
    }
    public string Name
    {
        get { return _name; }
        set
        {
            if (_name == value)
                return;
            _name = value;
            OnPropertyChanged();
        }
    }

    public string PropertyToBindTo
    {
        set { SetPropertToBindTo(value); }
    }

    #endregion 

    #region Methods
    public string GetPropertyToBindTo()
    {
        return _propertyName;
    }

    public void SetPropertToBindTo(string propertyName)
    {
        var prop = GetType().GetProperty(propertyName);
        if (prop == null)
            throw new Exception("Property : "+propertyName+" does not exist in this object {"+this.ToString()+"}.");
        _propertyName = propertyName;
    }



    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion Methods
}

Test Data

public ObservableCollection<TestChoosingPropertyToBind> Test
    {
        get
        {
            return new ObservableCollection<TestChoosingPropertyToBind>(
                new List<TestChoosingPropertyToBind>()
                {
                    new TestChoosingPropertyToBind(){EmailAddress = "Test@test.com", PropertyToBindTo = "EmailAddress"},
                    new TestChoosingPropertyToBind(){Name = "Test", PropertyToBindTo = "Name"}
                }
                );
        }
    }

An edited snippet of your data template with the custom behavior

<DataTemplate x:Key="VEGA_TokenTemplate">
        <Border x:Name="Bd" BorderBrush="Red" BorderThickness="1" Background="White" Padding="1" Margin="1,5" HorizontalAlignment="Stretch" SnapsToDevicePixels="True">
            <Grid VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="20" />
                </Grid.ColumnDefinitions>
                <TextBlock Text="{Binding WHAT_HERE}" HorizontalAlignment="Stretch" VerticalAlignment="Center" >
                    <i:Interaction.Behaviors>
                        <BehaviorLocationNamespace:MyCustomBehavior></BehaviorLocationNamespace:MyCustomBehavior>
                    </i:Interaction.Behaviors>
                </TextBlock>
                <Button Background="Transparent" 
                        Content="X" 
                        VerticalAlignment="Center" 
                        HorizontalAlignment="Center" 
                        FontSize="10" FontFamily="Berlin Sans FB" Grid.Column="1"  IsEnabled="True" />
            </Grid>
        </Border>
    </DataTemplate>

//Items Control usage
<ItemsControl ItemTemplate="{StaticResource VEGA_TokenTemplate}" ItemsSource="{Binding Test}">
链接地址: http://www.djcxy.com/p/44614.html

上一篇: 使用MVVM将Silverlight绑定到DataForm中的Combobox

下一篇: WPF如何评估一个属性进行绑定