在我的XAML中,我有一个只读ListView,右键单击listView项目,我想提供一个click-option,它将更新对象的属性并最终更新列表视图的“My Name”列。
假设我的listView在Primary.Xaml中。此xaml的DataContext是ObjectInfo。 Xaml有一个listView和一个ContextMenu,如下所示:
<ListView x:Name="lview" SelectedIndex="0" Width="{Binding ElementName=gridItems, Path=ActualWidth}" Height="{Binding ElementName=gridItems, Path=ActualHeight}" Style="{DynamicResource ListViewStyle}">
<ListView.ContextMenu>
<ContextMenu>
<MenuItem x:Name="mitem" Click="mitem_Click" >
<MenuItem.Header>
<Label HorizontalContentAlignment="Left" Content="My Name"/>
</MenuItem.Header>
</MenuItem>
</ContextMenu>
</ListView.ContextMenu>
<ListView.View>
<GridView ColumnHeaderContainerStyle="{StaticResource GridViewColumnHeaderStyle}">
<GridViewColumn Header="Id#" Width="80" DisplayMemberBinding="{Binding Id}" />
<GridViewColumn Header="Number#" Width="100" DisplayMemberBinding="{Binding Number}" />
<GridViewColumn Header="My Name" Width="80" DisplayMemberBinding="{Binding MyName}" />
</GridView>
</ListView.View>
因此,我的listView的DataContext是ObjectInfo,它将MyName作为只读属性。
public string MyName { get; private set; }
我正在加载这样的属性:
MyName = dr.GetString("DifferentObject" + "MyName");
这意味着我必须更新“DifferentObject”对象的属性并从Primary.Xaml监听更改。
这是我想要更新并绑定到我的ContextMenu中的“DifferentObject”的属性。
private static readonly PropertyInfo<bool> IsMyNameProperty = RegisterValueProperty<bool>(x => x.IsMyName);
public bool IsMyName
{
get { return GetProperty(IsMyNameProperty); }
set
{
SetProperty(IsMyNameProperty, value);
if (value)
{
SetProperty(MyNameIdProperty, UserId);
SetProperty(MyNameProperty, Name);
}
else
{
SetProperty(MyNameIdProperty, 0);
SetProperty(MyNameProperty, string.Empty);
}
}
}
我的xaml后面的代码,我打算做所有的逻辑和datacontext操作:
private void mitem_Click(object sender, RoutedEventArgs e)
{
var selectedItem = lview.SelectedItem as ObjectInfo;
var Name = GetInfo().Name;
if (selectedItem.MyName != Name)
{
var item = lview.DataContext as DifferentObject; //I have item as null
//after I get item, I will be able to assign true to IsMyName
}
}
原来如此!我的问题是,我如何为ContextMenu提供不同的DataContext?