Вопрос

In MainWindow class I have checkbox that controls property used by many objects like grids, listviews, etc in UserControls

    <CheckBox Content="Show objects ID" Name="showID" IsChecked="False" />

than there is property defined,

    public Visibility ShowObjectIDasVisibility
    {
        get { return showID.IsChecked.Equals(true) ? Visibility.Visible : Visibility.Collapsed; }
    }

I have some more like this to return boolean, width depending on what should be used on target control.

I managed to bind controls located in UserControl objects to use this property like this:

<TextBlock Visibility="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=ShowObjectIDasVisibility}" />

But it works only ones, while creating this TextBlock, than I can toggle checkbox as many times I like, and the TextBlock will stay visible or not depending on first value.

How should I do this properly? Thanks.

Это было полезно?

Решение

Instead of INotifyPropertyChanged interface you can use DependencyProperty:

public Visibility ShowObjectIDasVisibility
    {
        get { return (Visibility)GetValue(ShowObjectIDasVisibilityProperty); }
        set { SetValue(ShowObjectIDasVisibilityProperty, value); }
    }
    public static readonly DependencyProperty ShowObjectIDasVisibilityProperty =
        DependencyProperty.Register("ShowObjectIDasVisibility", typeof(Visibility), typeof(MainWindow), new PropertyMetadata(Visibility.Collapsed));

Now, to show/hide your TextBlock you need to change ShowObjectIDasVisibility value.

For example, you can do it by adding to checkbox Click="OnShowID_Click and in code behind

private void OnShowID_Click(object sender, RoutedEventArgs e)
    {
        ShowObjectIDasVisibility = ShowObjectIDasVisibility == System.Windows.Visibility.Visible ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible;
    }

Другие советы

if your binding is correct. you just need to make sure that your code class is implementing INotifyPropertyChanged interface in class binded to view and you are raising RaisePropertyChanged event in every checkbox state change. For more details look at example here.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top