C# 具有双向绑定的控件的更改属性
我有一个带有bool属性的自定义控件。该属性正在绑定带有弹出窗口的包含模板控件 XAML控件:C# 具有双向绑定的控件的更改属性,c#,.net,wpf,mvvm,binding,C#,.net,Wpf,Mvvm,Binding,我有一个带有bool属性的自定义控件。该属性正在绑定带有弹出窗口的包含模板控件 XAML控件: <controls:AutoCompleteTextBox x:Name="PART_Editor" IsEnabled="False" IsPopupOpen="{Binding IsAutocompletePopupOpen
<controls:AutoCompleteTextBox x:Name="PART_Editor"
IsEnabled="False"
IsPopupOpen="{Binding IsAutocompletePopupOpen}" />
绑定到模板控件中包含的元素:
public bool IsPopupOpen
{
get => (bool)GetValue(IsPopupOpenProperty);
set => SetValue(IsPopupOpenProperty, value);
}
public static readonly DependencyProperty IsPopupOpenProperty =
DependencyProperty.Register("IsPopupOpen", typeof(bool), typeof(AutoCompleteTextBox), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
<Popup x:Name="PART_AutoCompletePopup"
IsOpen="{Binding IsPopupOpen, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}" />
我需要在单击时更改属性IsPopupOpen。我决定在行为上这样做,但我需要禁用我的控制。因此,我将行为添加到控件的容器中
<Grid>
<controls:AutoCompleteTextBox x:Name="PART_Editor"
IsEnabled="False"
IsPopupOpen="{Binding IsAutocompletePopupOpen}"/>
<i:Interaction.Behaviors>
<behaviors:PopupContainerBehavior IsPopupOpen="{Binding IsAutocompletePopupOpen, Mode=TwoWay}" />
</i:Interaction.Behaviors>
</Grid>
行为准则:
public class PopupContainerBehavior : Behavior<UIElement>
{
public bool IsPopupOpen
{
get { return (bool)GetValue(IsPopupOpenProperty); }
set { SetValue(IsPopupOpenProperty, value); }
}
public static readonly DependencyProperty IsPopupOpenProperty =
DependencyProperty.Register("IsPopupOpen", typeof(bool), typeof(PopupContainerBehavior), new PropertyMetadata(false));
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.PreviewMouseLeftButtonDown += OnMouseLeftButtonUp;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.PreviewMouseLeftButtonDown -= OnMouseLeftButtonUp;
}
private void OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
IsPopupOpen = true;
}
}
公共类PopupContainerBehavior:行为
{
公共场所
{
获取{return(bool)GetValue(IsPopupOpenProperty);}
set{SetValue(IsPopupOpenProperty,value);}
}
公共静态只读从属属性IsPopupOpenProperty=
DependencyProperty.Register(“IsPopupPopen”、typeof(bool)、typeof(PopupContainerBehavior)、new PropertyMetadata(false));
受保护的覆盖无效附加()
{
base.onatached();
AssociatedObject.PreviewMouseLeftButtonDown+=OnMouseLeftButtonUp;
}
附加时受保护的覆盖无效()
{
base.OnDetaching();
AssociatedObject.PreviewMouseLeftButtonDown-=OnMouseLeftButtonUp;
}
MouseLeftButtonUp上的私有void(对象发送器,MouseButtonEventArgs e)
{
IsPopupOpen=true;
}
}
问题是属性首先变为true,然后立即变为false。通过SNOOP,您可以通过属性的闪烁值看到这一点。我认为问题在于双向绑定,但我不知道如何修复它。发生这种情况的原因是由于鼠标捕获
- 行为的
事件处理程序告诉PreviewMouseLeftButtonDown
弹出窗口打开
- 弹出窗口捕获鼠标
- 容器的其余单击事件将触发
- 容器将从弹出窗口中删除鼠标捕获
弹出窗口立即关闭
您可能想考虑让控件在禁用时打开<代码>弹出< /代码>,而不是试图从外部打开它。即使控件已禁用,也可以通过在需要交互的部分上设置
ishitestvisible
等,使其部分可单击