绑定只能在XAML中使用,而不能在后面的代码中使用

时间:2018-10-02 07:15:54

标签: vb.net xaml binding

我有2个文本框,一个名为烟雾警报,一个名为错误烟雾警报,当烟雾警报的输入发生变化并且f的值大于零时,我运行一个转换器,显示错误的烟雾警报,如果不是,我将其隐藏。如果我在XAML中声明了文本框,则有效,但如果我在后面的代码中声明了它们,则无效。我没有错误,我在做什么错了?

   <Grid>
        <ItemsControl x:Name="itemsControl" Margin="10">
            <!--<TextBox x:Name="SmokeAlarms" Width="100" FontSize="20" />
            <TextBox x:Name="FaultySmokeAlarms" Width="100" 
            Margin="0,10,0,0" FontSize="20"/>-->
        </ItemsControl>
    </Grid>

   Dim SmokeAlarms As New TextBox With {.Name = "SmokeAlarms", .Width = 200, .FontSize = 20}
    Dim FaultySmokeAlarms As New TextBox With {.Name = "FaultySmokeAlarms", .Width = 200, .FontSize = 20}



  Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        itemsControl.Items.Add(SmokeAlarms)
        itemsControl.Items.Add(FaultySmokeAlarms)

    End Sub

    Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
        Try
            Dim b As New Binding
            b.Converter = New IntegerToVisibilityConverter
            b.ElementName = "SmokeAlarms"
            b.Mode = BindingMode.TwoWay
            b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
            b.Path = New PropertyPath("Text")
            BindingOperations.SetBinding(FaultySmokeAlarms, VisibilityProperty, b)
        Catch ex As Exception
        End Try
    End Sub

1 个答案:

答案 0 :(得分:0)

将.ElementName更改为.Source,以获取后面的代码。