This is considered a constitutional convention, in that it's not an official, written-down rule, but it is generally expeted to be followed.
The convention that the government is seen to be accountable to House of Commons started in the 1700s, with the government of Sir Robert Walpole. In 1742, Sir Robert lost what he considered to be a vote of confidence in the government, and so he tendered his resignation to the king.
Since then, the convention has been that HM Government must always have the confidence of the House of Commons in order to govern. When a majority of MPs are from a single party, as is usually the case, such confidence is relatively straightforward for the leader of this party to receive.
When there is a hung parliament, when no party has an overall majority, things get a bit trickier. In this case, the Prime Minister will be whichever leader can get the support of enough parties to get a majority in the Commons. In 2010 and 2017, these both happened to also be the leaders of the largest parties (David Cameron and Theresa May, respectively). However, in 1923, Ramsay MacDonald became Prime Minister despite Labour being 67 seats behind the Conservatives, as the Liberals (with 158 seats) decided to support a Labour rather than a Conservative government.
To summarize: The Prime Minister is the person who can get the support of a majority in the House of Commons, and this is usually, though not necessarily, the leader of the largest party.