標題說明了一切。這是我嘗試的,但是當我點擊它們時,新按鈕什麼也不做。我對WPF很感興趣,所以你可以隨意轉發你可以看到的任何明顯的壞習慣。WPF爲每個新按鈕提供使用C#的相同單擊命令
UserInputPage.xaml
<Grid Name="UserInputGrid">
<Button Name="FindAddressButton_1" Grid.Row="0" Grid.Column="1" Margin="5,35,0,0" Width="30" Height="20" VerticalAlignment="Top" HorizontalAlignment="left" Click="ClickFindAddress">...</Button>
<Button Name="NewFileButton" Grid.Row="1" Margin="10,6,0,0" Width="Auto" Height="18" VerticalAlignment="Top" HorizontalAlignment="Left" Click="ClickNewBar">New Item</Button>
</Grid>
UserInputPage.xaml.cs
private void ClickNewBar (object sender, RoutedEventArgs e)
{
if (FilesList.Items.Count < MAX_ADDRESS_BARS)
{
CreateNewAddressBar();
CreateFindButton();
}
else
{
MessageBox.Show (ErrorMessages.MAX_ITEMS);
}
}
private void CreateFindButton()
{
Button newAddressButton = new Button();
newAddressButton.Name = buttonProperties.GetLatestRankedName();
newAddressButton.Content = AFindButtonsProperties.CONTENT;
newAddressButton.Command = buttonProperties.ButtonsAction;
UserInputGrid.Children.Add (newAddressButton);
}
AFindButtonsProperties.cs
public const int ROW = 0;
public const int COLUMN = 1;
public const double WIDTH = 30;
public const double HEIGHT = 20;
public const double MARGIN_INCREMENT = 22;
public const string CONTENT = "...";
public const string NAME = "FindAddressButton";
public readonly VerticalAlignment verticalAlignment = VerticalAlignment.Top;
public readonly HorizontalAlignment horizontalAlignment = HorizontalAlignment.Left;
public readonly ICommand ButtonsAction;
public AFindButtonsProperties (Grid inputGrid)
{
gridReference = inputGrid;
int notNeeded;
buttonReference = GetReferenceLastRankedButton (out notNeeded);
ButtonsAction = buttonReference.Command;
}
private Button GetReferenceLastRankedButton (out int lastRank)
{
Button outputButton = null;
int lastRankConstruction = 0;
foreach (var element in gridReference.Children)
{
Button currentButton = element as Button;
if (currentButton != null) //skipps elements that arent buttons
{
string[] choppedUp = currentButton.Name.ToString().Split ('_');
if (choppedUp.Length > 1 && //prevents exception for names not following the FindButton convention.
choppedUp[0].Contains (NAME))
{
int numberIsolated = Convert.ToInt16 (choppedUp[1]);
if (numberIsolated > lastRankConstruction)
{
outputButton = currentButton;
lastRank = numberIsolated;
}
}
}
}
if (outputButton == null)
{
throw new ViewElementNotFoundException ("Cant find any buttons in the grid reference which follow the naming convention.");
}
else
{
lastRank = lastRankConstruction;
return outputButton;
}
}
public string GetLatestRankedName()
{
int lastRank;
Button lastButton = GetReferenceLastRankedButton (out lastRank);
lastRank++;
string name = NAME + "_" + lastRank.ToString();
return name;
}
所以這是一個重複的問題,但繼承人我的查詢的答案:http://stackoverflow.com/questions/5102760/wpf-button-click-in-c-sharp-code?rq=1 –
如果你只是想要使用點擊事件爲什麼要打擾命令!我真的迷失在你的問題中! – Emad
由於其摘要工具提示,我認爲Command是點擊事件。你的回答非常好:) –