简体   繁体   English

WPF如何评估属性以进行绑定

[英]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. 我正在为我们的公司做一个自定义控件,我想将元素的DataTemplate定义到ResourceDictionary中,以实现更多通用性和外观处理。 My control has a ItemsSource property that contains all collection. 我的控件具有包含所有集合的ItemsSource属性。 I also have a DependencyProperty into my control that specificy the name of the property of current Item to bind on. 我的控件中也有一个DependencyProperty,它具体说明了要绑定的当前Item属性的名称。

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. 在此DataTemplate中,我想通过对依赖项属性的评估来替换WHAT_HERE标记。 For example, if I set "Email" on my dependency property, I would like the Binding to be like "Path=Email". 例如,如果我在依赖项属性上设置“ Email”,则希望绑定就像“ 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}">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM