我需要將一組文本框與從組合框中選擇的一些數據綁定,但我不想反映文本框到組合框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;
}
假設您的原始綁定是一些源視圖模型,我同意下面發佈的答案。您應該將綁定設置爲'OneWay'並清除源屬性,而不是目標屬性。這也將清除目標屬性,而不會破壞綁定。 –
如果由於某種原因你必須銷燬綁定並且稍後需要重新創建綁定,那麼在堆棧溢出解決這個確切場景時不會出現問題。例如,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 –
我將ComboBox的'SelectedItem'設置爲'null',並且它作品! 這是清除目標值的正確方法嗎? –