为什么我的UserControl中的TwoWay绑定只能在OneWay上工作?

问题描述

我有一个非常简单的切换样式UserControl。只是一个矩形的圆圈:

    <Grid MouseLeftButtonDown="Grid_MouseLeftButtonDown">
        <Rectangle x:Name="Body" Width="100" Height="50"  RadiusY="25" RadiusX="25" Fill="DarkGray"/>
        <Ellipse x:Name="Nipple" Width="46" Height="46" HorizontalAlignment="Center" VerticalAlignment="Center" Fill="DimGray" Margin="-50,0"/>
    </Grid>

...具有单个DependencyProperty“ IsOnProperty”

public static readonly DependencyProperty IsOnProperty = DependencyProperty.Register("IsOn",typeof(bool),typeof(MyToggleSwitch),new FrameworkPropertyMetadata(true,FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
    
    public bool IsOn
    {
        get { return (bool)GetValue(IsOnProperty); }
        set
        {
            SetValue(IsOnProperty,value);
            if (value)
            {
                Nipple.Margin = Offset_Right;
            }
            else
            {
                Nipple.Margin = Offset_Left;
            }
        }
    }
    

在MainWindow中,我有一个属性“ IsOn” ...

bool _ison;
public bool IsOn
{ 
    get
    {
        return _ison;
    }
    set
    {
        _ison = value;
        OnPropertyChanged("IsOn");
    }
}

...然后我可以将DependencyProperty绑定到该值:

    <StackPanel>
        <local:MyToggleSwitch x:Name="Toggle" IsOn="{Binding IsOn,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}"/>
    </StackPanel>

现在,我可以高兴地单击控件,并惊奇地看到“乳头”如何翻转以及底层DependecyProperty如何来回变化。太棒了!

在这里变得很奇怪: 在我的UserControl中,我进行了数据绑定TwoWay ...

IsOn="{Binding IsOn,Mode=TwoWay}"

...但是,如果底层布尔值在代码中的其他位置发生了变化,则不会将更改传播回我的UserControl。

我的DependencyProperty有问题吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)