Двусторонняя привязка для ContentControl - PullRequest
2 голосов
/ 04 июня 2010

Я создаю редактор пар ключ / значение и хотел бы, чтобы у значения был собственный шаблон, основанный на типе данных.

<TextBox x:Uid="txtKey" x:Name="txtKey" Grid.Column="1" Grid.Row="0" Text="{Binding ElementName=This, Path=KeyValuePair.Key}" VerticalAlignment="Top"/>
<ContentControl Grid.Column="1" Grid.Row="1"
           x:Uid="ContentControl1" x:Name="ContentControl1" 
           Content="{Binding ElementName=This, Path=KeyValuePair.Value}" 
           LostFocus="ContentControl1_LostFocus"  
           DataContextChanged="ContentControl1_DataContextChanged"   />

Код для основного класса выглядит следующим образом:

public partial class KeyValueControl : ControlBase
{
    private System.Collections.DictionaryEntry _dictionaryEntry;
    private KeyValuePairObjectObject _KeyValuePair = new KeyValuePairObjectObject();
    private DataTemplate _editorDataTemplate;
    private Caelum.Libraries.Ui.Editors.Resources resources = new Editors.Resources();

    public DataTemplate EditorDataTemplate
    {
        get { return _editorDataTemplate; }
        set { _editorDataTemplate = value; SendPropertyChanged("EditorDataTemplate"); }
    }

    public KeyValuePairObjectObject KeyValuePair
    {
        get { return _KeyValuePair; }
        set { _KeyValuePair = value; SendPropertyChanged("KeyValuePair"); }
    }


    public KeyValueControl()
    {
        InitializeComponent();
        this.DataUpdated += new DataUpdatedHander(KeyValueControl_DataUpdated);
        DataContextChanged += new DependencyPropertyChangedEventHandler(KeyValueControl_DataContextChanged);
    }

    void KeyValueControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
    }

    public override void Save()
    {
        base.Save();
    }

    void KeyValueControl_DataUpdated(object sender, object data)
    {
        if (Data != null)
        {
            _dictionaryEntry = (System.Collections.DictionaryEntry)Data;
            KeyValuePair.Key = _dictionaryEntry.Key;
            KeyValuePair.Value = _dictionaryEntry.Value;

            if (KeyValuePair.Value != null)
            {
                EditorDataTemplate = resources.GetDataTemplate(_dictionaryEntry.Value.GetType());
                ContentControl1.ContentTemplate = EditorDataTemplate;
            }               
        }
    }


}

Шаблоны данных выбираются через класс ресурсов:

public DataTemplate GetDataTemplate(Type type)
    {

        if (type == typeof(string))
        {
            return TextInlineEditorTemplate;
        }
        if (type == typeof(bool))
        {
            return BooleanInlineEditorTemplate;
        }

        return null;
    }

DataTemplate, отображаемый для строки:

<DataTemplate x:Uid="TextInlineEditorTemplate" x:Key="TextInlineEditorTemplate"  >
    <Grid>
        <TextBox x:Uid="txtTextIET1" x:Name="txtTextIET1" Width="300" Text="{Binding Path=DataContext, Mode=TwoWay, RelativeSource={RelativeSource Self}, BindsDirectlyToSource=True, UpdateSourceTrigger=PropertyChanged}" />
    </Grid>
</DataTemplate>

Данные связывают OK с ключами TextBox (txtKey) и DataTemplate TextBox (txtTextIET1), но изменение значения txtTextIET1 не вызовет установщик свойства KeyValuePair. Я не смог найти никаких примеров этого сценария, поэтому любая помощь будет оценена.

1 Ответ

0 голосов
/ 04 июня 2010

Разве это не сработало для вас

<DataTemplate x:Uid="TextInlineEditorTemplate" x:Key="TextInlineEditorTemplate"  > 
    <Grid> 
        <TextBox x:Uid="txtTextIET1" x:Name="txtTextIET1" Width="300" Text="{Binding}" /> 
    </Grid> 
</DataTemplate>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...