将复选框绑定到IronPython中的字符串

时间:2011-07-04 19:58:55

标签: python visual-studio-2010 data-binding ironpython

如何将复选框绑定到字符串,以便在选中/取消选中复选框时,字符串的值会更改?我有这个(CheckAll作为我的复选框):

class MyWindow(Window):
    def __init__(self):
        wpf.LoadComponent(self, 'BioApp1.xaml')
        openDialog = SequenceFileOperations()
        self.Sequences = openDialog.Open()
        object = MyObjects(self.Sequences)
        self.CheckAll.DataContext = object
        self.IDLabel.DataContext = object


class MyObjects(object):
    def __init__(self, Sequences):
        self.CurrentSeq = Sequences[0]
        self.ID = self.CurrentSeq.ID 

<Label Height="28" HorizontalAlignment="Left" Margin="152,221,0,0" VerticalAlignment="Top" Width="98" Name="IDLabel" Content="{Binding Path=ID}"/>

我希望在取消选中该复选框时,标签应显示序列ID,但检查时,它应该只显示“全部”。为此,我需要将CurrentSeq的ID属性更改为“All”。我如何通过数据绑定来做到这一点?有没有其他方法可以做到这一点?

编辑:我觉得自己很蠢,但我无法让它发挥作用。我一直在尝试遵循关于使用getter / setter的建议,但我想我不够了解。在做任何更复杂的事情之前,我只想在勾选复选框时禁用按钮,并在取消选中时启用它。这就是我写的:

class MyWindow(Window):
    def __init__(self):
    wpf.LoadComponent(self, 'App1.xaml')
    object = BindingClass(self.Check, self.PreviousBtn)
    self.PreviousBtn.DataContext = object 

class BindingClass(object):
    def __init__(self, Check, PreviousBtn):
        self.Check = Check
        self.PreviousBtn = PreviousBtn

    def GetEnabledConverter(self):
        if self.CheckAll.IsChecked:
            return self.PreviousBtn.IsEnabled

    def SetEnabledConverter(self):
        if self.CheckAll.IsChecked:
            self.PreviousBtn.IsEnabled = False
        else:
            self.PreviousBtn.IsEnabled = True

    EnabledConverter = property(GetEnabledConverter, SetEnabledConverter)

<Button Content="Previous" IsEnabled="{Binding Path=EnabledConverter}" />

不幸的是,没有错误但也没有效果。代码没有做任何事情。如果你能帮助我,我真的很感激。

EDIT2:使用notify_property,我尝试了这个:

class MyWindow(Window):
    def __init__(self):
        wpf.LoadComponent(self, 'Test.xaml')
        c = Converters(self.check1, self.Button)
        self.Button.DataContext = c

class Converters(NotifyPropertyChangedBase):
    def __init__(self, check, button):
        super(Converters, self).__init__()
        self.Check = check
        self.Button = button


    @notify_property
    def ButtonEnabled(self):
        return self.Button.IsEnabled

    @ButtonEnabled.setter
    def ButtonEnabled(self):
        if self.Check.IsChecked:
            self.Button.IsEnabled = False
        else:
            self.Button.IsEnabled = True

结果仍然相同:没有效果。我只是无法理解问题所在。

1 个答案:

答案 0 :(得分:1)

我会使用Converter

修改

您可以在Python中实现转换器:

class BoolToVisibilityConverter(IValueConverter):

    def Convert(self, value, targetType, parameter, culture):
        return Visibility.Visible if value != val else Visibility.Collapsed

上次我在IronPython中使用WPF时,您无法直接在.xaml中使用它。我不确定它是否在2.7中有所改进。

另一种可能性是在其setter / getter中添加另一个执行转换(converted_ID)的属性。考虑更多,我会这样做,因为代码在一个地方。

编辑2:

请确保您使用的是notify_property而不是经典的Python属性。