2017-06-28 57 views
0

我需要将一组文本框与从组合框中选择的一些数据绑定,但我不想反映文本框到组合框ItemsSource上的任何更改,所以我将绑定模式设置为OneTime,它工作正常,但我有清除文本框的内容的按钮,点击的时候让他们清楚,即使我从组合框中选择一个项目:以编程方式设置与TextBoxes绑定的一种方式?

XAML:

<Grid Name="mGrd" DataContext="{Binding ElementName=cmbBooks, Path=SelectedItem}" Grid.Column="1"> 
      <Grid.ColumnDefinitions> 
       <ColumnDefinition/> 
       <ColumnDefinition/> 
      </Grid.ColumnDefinitions> 
      <Grid.RowDefinitions> 
       <RowDefinition/> 
       <RowDefinition/> 
       <RowDefinition/> 
       <RowDefinition/> 
       <RowDefinition/> 
       <RowDefinition/> 
      </Grid.RowDefinitions> 
      <ComboBox Name="cmbBooks" Grid.ColumnSpan="2" DisplayMemberPath="Title"/> 

      <Label Grid.Row="1">Id</Label> 
      <TextBox Grid.Row="1" Grid.Column="1" Name="txtId" Text="{Binding Path=Id, Mode=OneTime}"/> 

      <Label Grid.Row="2">Title</Label> 
      <TextBox Grid.Column="1" Grid.Row="2" Name="txtTitle" Text="{Binding Path=Title, Mode=OneTime}"/> 

      <Label Grid.Row="3">#Pages</Label> 
      <TextBox Grid.Column="1" Grid.Row="3" Name="txtPCount" Text="{Binding Path=PagesCount, Mode=OneTime}"/> 

      <Label Grid.Row="4">Is Published</Label> 
      <CheckBox Grid.Column="1" Grid.Row="4" VerticalAlignment="Center" Name="chkPblshd" IsChecked="{Binding Path=IsPublished, Mode=OneTime}"/> 

      <StackPanel Grid.Row="5" Orientation="Horizontal"> 
       <Button Name="btnClear" Click="btnClear_Click" Background="Red" Foreground="White" FontWeight="Bold" Margin="2">X</Button> 
       <Button Name="btnAddBook" Click="btnAddBook_Click">Add new Book</Button> 
      </StackPanel> 
     </Grid> 

清除按钮:

private void btnClear_Click(object sender, RoutedEventArgs e) 
     { 
      txtId.Text = txtPCount.Text = txtTitle.Text = ""; 
      chkPblshd.IsChecked = false; 
     } 
+0

假设您的原始绑定是一些源视图模型,我同意下面发布的答案。您应该将绑定设置为'OneWay'并清除源属性,而不是目标属性。这也将清除目标属性,而不会破坏绑定。 –

+0

如果由于某种原因你必须销毁绑定并且稍后需要重新创建绑定,那么在堆栈溢出解决这个确切场景时不会出现问题。例如,https://stackoverflow.com/questions/2938656/binding-properties-in-code-behind,https://stackoverflow.com/questions/10131637/binding-string-property-in-code-behind-textblock ,以及https://stackoverflow.com/questions/4966967/wpf-how-to-set-checkbox-ischecked-binding-in-code-behind –

+0

我将ComboBox的'SelectedItem'设置为'null',并且它作品! 这是清除目标值的正确方法吗? –

回答

0

使用绑定模式OneWay而不是OneTime,因此模型中的更改将反映在UI中。

不幸的是,这是不够的,因为你正在设置Text财产手动。这是破坏你的绑定!而是清除绑定值中的文本。

+0

已更改,仍然没有变化 –

+0

@MohamedAhmed哦,我没有看到你清晰的按钮。你不能改变这样的文本!请参阅我的编辑 – BradleyDotNET

+0

“文本”属性不是绑定值,这就是我如何清除其值?! –