Visibility Autobinding with naming convention

爱⌒轻易说出口 提交于 2019-12-03 05:09:57

You could use this approach if you wanted, it's perfectly reasonable. Another approach is to use a Border with the same name as a boolean property on your view model. Caliburn.Micro will set the visibility of the Border based on the value of the boolean property.

<Border x:Name="ControlIsVisible">
  <TextBox x:Name="MyControl" ... />
</Border>
Malcolm

If you want a general solution, this is what I ended up with, based on: Adding a convention for IsEnabled to Caliburn.Micro

Note the overriding of BindActions as well as BindProperties so that you can check for Visibility on things that have actions bound to them.

    protected override void Configure()
    {
        base.Configure();

        ConventionManager.AddElementConvention<UIElement>(UIElement.VisibilityProperty, "Visibility", "VisibilityChanged");

        var baseBindProperties = ViewModelBinder.BindProperties;
        ViewModelBinder.BindProperties =
            (frameWorkElements, viewModel) =>
            {
                BindVisiblityProperties(frameWorkElements, viewModel);
                return baseBindProperties(frameWorkElements, viewModel);
            };

        // Need to override BindActions as well, as it's called first and filters out anything it binds to before
        // BindProperties is called.
        var baseBindActions = ViewModelBinder.BindActions;
        ViewModelBinder.BindActions =
            (frameWorkElements, viewModel) =>
            {
                BindVisiblityProperties(frameWorkElements, viewModel);
                return baseBindActions(frameWorkElements, viewModel);
            };

    }

    void BindVisiblityProperties(IEnumerable<FrameworkElement> frameWorkElements, Type viewModel)
    {
        foreach (var frameworkElement in frameWorkElements)
        {
            var propertyName = frameworkElement.Name + "IsVisible";
            var property = viewModel.GetPropertyCaseInsensitive(propertyName);
            if (property != null)
            {
                var convention = ConventionManager
                    .GetElementConvention(typeof(FrameworkElement));
                ConventionManager.SetBindingWithoutBindingOverwrite(
                    viewModel,
                    propertyName,
                    property,
                    frameworkElement,
                    convention,
                    convention.GetBindableProperty(frameworkElement));
            }
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!