And*_*mes 5 c# wpf prism mvvm routed-events
我有一个ViewModel集合,它们使用样式呈现为制表符,以拉出要在选项卡上显示的相关内容:
public class TabViewModel : DependencyObject
{
public object Content
{
get { return (object)GetValue(ContentProperty); }
set
{
SetValue(ContentProperty, value);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是TabControl:
<TabControl
ItemsSource={Binding MyCollectionOfTabViewModels}"
ItemContainerStyle="{StaticResource TabItemStyle}" />
Run Code Online (Sandbox Code Playgroud)
这是风格
<Style TargetType="TabItem" x:Key="TabItemStyle">
<Setter Property="Content" Value="{Binding Content}"/>
</Style>
Run Code Online (Sandbox Code Playgroud)
我们正在创建一个usercontrol实例,并将TabViewModel的"Content"属性设置为该属性,以便userItrol显示在TabItem的Content区域中.
MyCollectionOfViewModels.Add(new TabViewModel()
{
Content = new MyUserControl();
});
Run Code Online (Sandbox Code Playgroud)
我的问题是,我想允许添加到TabViewModel的Content属性的MyUserControl(或其任何子控件)引发TabViewModel处理的事件.
谁知道我会怎么做?
我们已经尝试过使用RoutedEvents和RoutedCommands,但是无法让任何东西100%工作并让它与MVVM兼容.我真的认为这可以通过RoutedEvent或RoutedCommand完成,但我似乎无法让它工作.
注意:我已经删除了一些相关的Prism特定代码,但是如果你想知道我们为什么做这么愚蠢的事情,那是因为我们试图通过使用Prism的RegionManager来保持控制不可知.
您可以将 State 属性添加到 TabViewModel 中,并检查 DependencyPropertyChanged 事件。
所以想象一下以下枚举:
public enum TabViewModelState
{
True,
False,
FileNotFound
}
Run Code Online (Sandbox Code Playgroud)
然后将 State 属性添加到该枚举的 TabViewModel 中:
public static readonly DependencyProperty StateProperty =
DependencyProperty.Register("State", typeof(TabViewModelState), typeof(TabViewModel), new PropertyMetadata(OnStateChanged));
private static void OnStateChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
TabViewModel viewModel= (TabViewModel)obj;
//Do stuff with your viewModel
}
Run Code Online (Sandbox Code Playgroud)
在控件中使用对此属性的双向绑定:
<CheckBox Checked="{Binding Path=State, Converter={StaticResource StateToBooleanConverter}, Mode=TwoWay}" />
Run Code Online (Sandbox Code Playgroud)
最后但并非最不重要的一点是实现转换器,该转换器将在控件所需的原始值之间进行转换。(在我的示例中 boolean <--> TabViewModelState):
public class StateToBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
TabViewModelState state = (TabViewModelState) value;
return state == TabViewModelState.True;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
bool result = (bool) value;
return result ? TabViewModelState.True : TabViewModelState.False;
}
}
Run Code Online (Sandbox Code Playgroud)
现在您有了一个由 UI 管理的 State 属性,并在需要响应时抛出更改的事件。
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
4481 次 |
| 最近记录: |