使用自定义控件和DataTemplate绑定

时间:2015-12-07 11:21:14

标签: c# wpf binding datatemplate

我知道这个问题一直被问到,我已经对我的代码进行了很多建议的更改,但直到现在似乎没有任何效果。基本上我想扩展一些具有某些属性的控件。最简单的示例是带有新属性 IsInEditMode TextBox

List<Form1> form1List = new List<Form1>();
for (int i = 0; i < 10; i++)
{
    Form1 frm = new Form1();
    frm.Name = "Form1_Instance_" + i.ToString();
    frm.Text = frm.Name;
    frm.Tag = i;
    // Do not show it
    // frm.Show(); 
    // Add it to your list
    form1List.Add(frm);
}

// Now suppose that your code has a TextBox from which your user types the ID of the form

string temp = TextBox1.Text;
int num;
if (Int32.TryParse(temp, out num))
{
    if(num >= 0 && num <= 9)        
    {
       Form1 f = form1List.FirstOrDefault(x => x.Tag.ToString() == num.ToString());
       if(f != null)
           f.Show();
    }
}

相应的DataTemplate

public class EditableTextBox : TextBox
{
    public static readonly DependencyProperty IsInEditModeProperty =
     DependencyProperty.Register("IsInEditMode", typeof(bool), typeof(EditableTextBox),
          new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, (o, e) => ((EditableTextBox)o).IsInEditModeChanged(e)));

    private void IsInEditModeChanged(DependencyPropertyChangedEventArgs e)
    {
        IsInEditMode = (bool)e.NewValue;
    }

    [Bindable(true)]
    public bool IsInEditMode
    {
        get { return (bool)GetValue(IsInEditModeProperty); }
        set { SetValue(IsInEditModeProperty, value); }
    }
}

控件绑定到viewmodel属性,如此

<Style TargetType="controls:EditableTextBox" BasedOn="{StaticResource {x:Type TextBox}}">
    <Setter Property="Background" Value="{x:Null}"/>
    <Setter Property="BorderBrush" Value="{StaticResource LuculusDarkGrayBrush}"/>
    <Setter Property="BorderThickness" Value="1"/>
    <Setter Property="Foreground" Value="{StaticResource LuculusBlueBrush}"/>
    <Setter Property="FontWeight" Value="Normal"/>
    <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="controls:EditableTextBox">
                <TextBox x:Name="edTextBox" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" FontWeight="{TemplateBinding FontWeight}"
                        Background="{TemplateBinding Background}" SnapsToDevicePixels="True" Foreground="{TemplateBinding Foreground}" Text="{TemplateBinding Text}"/>

                <ControlTemplate.Triggers>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsInEditMode" Value="False"/>
                        </MultiTrigger.Conditions>
                        <Setter Property="BorderThickness" Value="0" TargetName="edTextBox" />
                        <Setter Property="Cursor" Value="Arrow" TargetName="edTextBox"/>
                        <Setter Property="IsReadOnly" Value="True" TargetName="edTextBox"/>
                    </MultiTrigger>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsInEditMode" Value="True"/>
                            <Condition Property="IsKeyboardFocusWithin" Value="True"/>
                        </MultiTrigger.Conditions>
                        <Setter Property="FontWeight" Value="Bold" TargetName="edTextBox"/>
                    </MultiTrigger>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsInEditMode" Value="True"/>
                        </MultiTrigger.Conditions>
                        <Setter Property="IsReadOnly" Value="False" TargetName="edTextBox"/>
                    </MultiTrigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

绑定不起作用。如果我直接输入布尔值,则行为与预期一致。

提前致谢

乔恩

1 个答案:

答案 0 :(得分:1)

您无需使用IsInEditModeChanged,只需删除此部分即可。另外,删除BindableAttribute。

不要忘记为您的模型实施INotifyPropertyChanged。我测试了这个套件,它工作正常。控制:

public static readonly DependencyProperty IsInEditModeProperty =
 DependencyProperty.Register("IsInEditMode", typeof(bool), typeof(EditableTextBox),
 new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

public bool IsInEditMode
{
    get { return (bool)GetValue(IsInEditModeProperty); }
    set { SetValue(IsInEditModeProperty, value); }
}

绑定测试:

<wpfApplication4:EditableTextBox IsInEditMode="{Binding Path=EditMode, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}">

视图模型:

private bool editMode;
public bool EditMode
{
    get { return editMode; }
    set
    {
        editMode = value;
        OnPropertyChanged();
    }
}