在代码中重置绑定

本文关键字:绑定 代码 | 更新日期: 2023-09-27 18:18:25

我正在编写一个能够使用此切换语言的应用程序。我还有一个combox,它有两个功能:

  • 如果在组合框中没有选择项目,则提供帮助文本(参见此)
  • 项目可通过复选框选择(见此)

我的组合框看起来像

<Grid>
    <ComboBox x:Name="MyCB" SelectionChanged="OnCbObjectsSelectionChanged" ...>
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <CheckBox IsChecked="{Binding IsSelected}" Checked="OnCbObjectCheckBoxChecked" Unchecked="OnCbObjectCheckBoxChecked"  Width="20" />
                    <TextBlock Text="{Binding Value}" Width="100" />
                </StackPanel>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>
    <TextBlock Visibility="{Binding SelectedItem, ElementName=MyCB, Converter={StaticResource Null2Vis}}"
        IsHitTestVisible="False"
        VerticalAlignment="Center"
        Name="tbObjects"
        Text="{ns:Loc Var1}"
        FontSize="20"
        Foreground="Gray"/>
    </Grid>

I暂时停用了return Visibility.Visible;的变换器,没有效果。

每当我选中一些复选框时,组合框。设置Text属性,并覆盖来自ns:Loc的绑定。如果所有复选框都未选中,我如何在代码中再次设置它?

private void OnCbObjectCheckBoxChecked(object sender, RoutedEventArgs e)
{
    StringBuilder sb = new StringBuilder();
    foreach (var cbObject in MyCB.Items)
        if (cbObject.IsSelected)
            sb.AppendFormat("{0}, ", cbObject.Value);
    tbObjects.Text = sb.ToString().Trim().TrimEnd(',');
    if (tbObjects.Text == "")
    {
        Binding myBinding = new Binding();
        myBinding.Source = TranslationSource.Instance["Var1"]; // <- this does not work :/
        myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
        BindingOperations.SetBinding(tbObjects, TextBox.TextProperty, myBinding);
        tbObjects.Foreground = new SolidColorBrush(Colors.Gray);
    }
}

当所有复选框都未选中时,组合框中没有文本。我错过了什么?


编辑:添加TextBox元素到代码

在代码中重置绑定

如果我正确理解您的代码以恢复本地化绑定,您不需要重新定义Binding -它应该足以使用LocExtension与适当的参数,因为它派生自Binding:

if (tbObjects.Text == "")
{
    var myBinding = new LocExtension("Var1");
    BindingOperations.SetBinding(tbObjects, TextBox.TextProperty, myBinding);
    tbObjects.Foreground = new SolidColorBrush(Colors.Gray);
}

但是如果出于某种原因你仍然想重新定义Binding,它应该是这样的:

if (tbObjects.Text == "")
{
    Binding myBinding = new Binding("[Var1]");
    myBinding.Source = TranslationSource.Instance;
    myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
    BindingOperations.SetBinding(tbObjects, TextBox.TextProperty, myBinding);
    tbObjects.Foreground = new SolidColorBrush(Colors.Gray);
}

注意,绑定的源是TranslationSource.Instance,路径应该是"[Var1]"用"Var1"参数指示索引器

<标题>边注h1> 于TranslationSource.Item[string]索引器是只读的,所以设置Binding.UpdateSourceTrigger是多余的。此外,出于同样的原因,我将Binding.Mode设置为OneWay