在我的项目中,我需要将ui元素的可见性绑定到bool属性,因为您知道caliburn.micro具有约定“CanName”,所以我想添加我自己的自定义约定。 然后我发现[可见性自动绑定与命名约定我在我的项目中添加此代码,但它不起作用和约定“CanName”也不起作用。
ConventionManager.AddElementConvention<FrameworkElement>(Control.VisibilityProperty, "Visibility", "IsVisible");
var baseBindProperties = ViewModelBinder.BindProperties;
ViewModelBinder.BindProperties = (frameWorkElements, viewModel) =>
{
BindVisiblityProperties(frameWorkElements, viewModel);
return baseBindProperties(frameWorkElements, viewModel);
};
static void BindVisiblityProperties(IEnumerable<FrameworkElement> items, Type viewModel)
{
foreach (FrameworkElement element in items)
{
string PropertyName = element.Name + "IsVisible";
var property = viewModel.GetPropertyCaseInsensitive(PropertyName);
if (property != null)
{
var convention = ConventionManager.GetElementConvention(typeof(FrameworkElement));
ConventionManager.SetBindingWithoutBindingOverwrite(viewModel, PropertyName, property,
element, convention, convention.GetBindableProperty(element));
}
}
}
任何人都知道这段代码有什么问题吗?
答案 0 :(得分:6)
我在我的项目中使用本公约没有任何问题。这是一个演练:
在AppBootstrapper.cs
中,您在其他特定公约中包含了元素公约
private static void AddCustomConventions()
{
ConventionManager.AddElementConvention<FrameworkElement>(Control.VisibilityProperty, "Visibility", "IsVisible");
var baseBindProperties = ViewModelBinder.BindProperties;
ViewModelBinder.BindProperties = (frameWorkElements, viewModel) =>
{
BindVisiblityProperties(frameWorkElements, viewModel);
return baseBindProperties(frameWorkElements, viewModel);
};
}
和你的助手方法:
private static void BindVisiblityProperties(IEnumerable<FrameworkElement> items, Type viewModel)
{
foreach (FrameworkElement element in items)
{
string PropertyName = element.Name + "IsVisible";
var property = viewModel.GetPropertyCaseInsensitive(PropertyName);
if (property != null)
{
var convention = ConventionManager.GetElementConvention(typeof(FrameworkElement));
ConventionManager.SetBindingWithoutBindingOverwrite(
viewModel, PropertyName, property, element, convention, convention.GetBindableProperty(element));
}
}
}
在PageView.xaml
放置您的控件并提供x:Name
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<Button x:Name="StartRecord">start</Button>
<Button x:Name="StopRecord">stop</Button>
<Button x:Name="Foo">foo</Button>
<Button x:Name="Bar">bar</Button>
</StackPanel>
在PageViewModel.cs
public property
内bool
类型public bool FooIsVisible { get { return true; } }
public bool BarIsVisible { get { return false; } }
后缀为IsVisible
{{1}}