[英]Binding Click action to custom xaml component
我在XAML中具有以下自定義控件:
<Button x:Name="button" HorizontalAlignment="Left" Margin="0,0,0,0" VerticalAlignment="Center" Width="200">
<StackPanel Orientation="Horizontal" Width="170">
<TextBlock Text="" FontFamily="Segoe UI Symbol" Visibility="{Binding isFolder, Converter={StaticResource BooleanToVisibilityConverter}}"/>
<TextBlock Text="" FontFamily="Segoe UI Symbol" Foreground="Gold" Visibility="{Binding isFolder, Converter={StaticResource InverseBooleanToVisibilityConverter}}"/>
<TextBlock Text="{Binding title}" Margin="5,0" Foreground="Black"/>
</StackPanel>
我想在isFolder上綁定點擊動作。 因此,我創建了一個xaml頁面,並在后面的代碼中添加了控件,如下所示:
MyControl item = new MyControl();
item.DataContext = context;
// item.click += context.isFolder ? folderAction : nonFolderAction
沒有item.click。 如何根據布爾值將委托添加到點擊?
您可以使用relaycommands,在其中可以指定執行命令的條件。
例如:(在您的情況下)
在您的視圖模型中:(執行此操作)
private RelayCommand myCommandInViewModel;
public RelayCommand MyCommandInViewModel
{
get { return myCommandInViewModel?? (myCommandInViewModel= new RelayCommand(myCommandInViewModelAction,()=> { return isFolder; })); }
}
其中myCommandInViewModelAction具有您的方法定義。
以上是建議的做法。 否則,您可以在button.Click事件中的另一種方式中獲取發送者的數據上下文,並在其中檢查isFolder屬性。
private void someClickEvent(object sender, RoutedEventArgs e)
{
var buttonDataContext = (sender as Button).DataContext;
if(buttonDataContext.isFolder)
{
doSomeThing();
}
else
{
return;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.